Search Results

Search found 138 results on 6 pages for 'serialversionuid'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Use the serialVersionUID or suppress warnings?

    - by Okami
    Dear all, first thing to note is the serialVersionUID of a class implementing Interface Serializable is not in question. What if we create a class that for example extends HttpServlet? It also should have a serialVersionUID. If someone knows that this object will never be serialized should he define it or add an annotation to suppress those warnings? What would you do and why? Thanks for sharing your thoughts. Okami

    Read the article

  • SerialVersionUID with "private static final long" still gets InvalidClassException

    - by Buggieboy
    I have compiled and jarred the various projects in my Java application, generating serialVersionUIDs automatically through Eclipse for all my classes derived from Serializable. I read the answers to this question, and verified that serialVersionUids are all private static final long. Nevertheless, I get an error like this when I try to run: java.io.InvalidClassException: com.acme.product.Widget; local class incompatible: stream classdesc serialVersionUID = 5226096973188250357, local class serialVersionUID = -5432967318654384362 What am I missing?

    Read the article

  • Is it a good practice to suppress warnings?

    - by Chris Cooper
    Sometimes while writing Java in Eclipse, I write code that generates warnings. A common one is this, which I get when extending the Exception class: public class NumberDivideException extends Exception { public NumberDivideException() { super("Illegal complex number operation!"); } public NumberDivideException(String s) { super(s); } } // end NumberDivideException The warning: The serializable class NumberDivideException does not declare a static final serialVersionUID field of type long. I know this warning is caused by my failure to... well, it says right above. I could solve it by including the serialVersionUID, but this is a one hour tiny assignment for school; I don't plan on serializing it anytime soon... The other option, of course, is to let Eclipse add @SuppressWarnings("serial"). But every time my mouse hovers over the Suppress option, I feel a little guilty. For programming in general, is it a good habit to suppress warnings? (Also, as a side question, is adding a "generated" serialVersionUID like serialVersionUID = -1049317663306637382L; the proper way to add a serialVersionUID, or do I have to determine the number some other way?)

    Read the article

  • ValidationException class version mismatch

    - by suszterpatt
    I have a simple EJB application that I can deploy and test on a local WebLogic instance (v10.3.0.0) without problems. I need to deploy this on a remote WL server (v10.3.3.0), and test it from a local machine. Deployment is successful, but when I try to run any of the clients from JDeveloper, I get this error: <2010.06.02. 16:08:36 CEST> <Error> <RJVM> <BEA-000503> <Incoming message header or abbreviation processing failed java.io.InvalidClassException: org.eclipse.persistence.exceptions.ValidationException; local class incompatible: stream classdesc serialVersionUID = 3793659634176227230, local class serialVersionUID = -7605463488982202416 java.io.InvalidClassException: org.eclipse.persistence.exceptions.ValidationException; local class incompatible: stream classdesc serialVersionUID = 3793659634176227230, local class serialVersionUID = -7605463488982202416 at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:562) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) at weblogic.rjvm.ClassTableEntry.readExternal(ClassTableEntry.java:36) at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1792) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) at weblogic.rjvm.InboundMsgAbbrev.readObject(InboundMsgAbbrev.java:65) at weblogic.rjvm.InboundMsgAbbrev.read(InboundMsgAbbrev.java:37) at weblogic.rjvm.MsgAbbrevJVMConnection.readMsgAbbrevs(MsgAbbrevJVMConnection.java:227) at weblogic.rjvm.MsgAbbrevInputStream.init(MsgAbbrevInputStream.java:173) at weblogic.rjvm.MsgAbbrevJVMConnection.dispatch(MsgAbbrevJVMConnection.java:439) at weblogic.rjvm.t3.MuxableSocketT3.dispatch(MuxableSocketT3.java:322) at weblogic.socket.AbstractMuxableSocket.dispatch(AbstractMuxableSocket.java:394) at weblogic.socket.SocketMuxer.readReadySocketOnce(SocketMuxer.java:917) at weblogic.socket.SocketMuxer.readReadySocket(SocketMuxer.java:849) at weblogic.socket.JavaSocketMuxer.processSockets(JavaSocketMuxer.java:283) at weblogic.socket.SocketReaderRequest.run(SocketReaderRequest.java:29) at weblogic.work.ExecuteRequestAdapter.execute(ExecuteRequestAdapter.java:21) at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:145) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:117) Can anyone explain why I'm getting this error, and what I can do to resolve it?

    Read the article

  • java serialization problems with different JVMs

    - by Alberto
    I am having trouble using serialization in Java. I've searched the web for a solution but haven't found an answer yet. The problem is this - I have a Java library (I have the code and I export it to an archive prior to executing the code) which I need to use with two differents JVMs. One JVM is on the server (Ubuntu, running Java(TM) JRE SE Runtime Environment (build 1.7.0_09-b05)) and the other on Android 2.3.3. I compiled the library in Java 1.6. Now, I am trying to import to the client, an object exported from the server, but I receive this error: java.io.InvalidClassException: [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;; Incompatible class (SUID): [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =-359311387972759020L; but expected [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =1920571045915494592L; I do have an explicit serial version UID declared on the class MultilayerPerceptron$NeuralEnd, like this: protected class NeuralEnd extends NeuralConnection { private static final long serialVersionUID = 7305185603191183338L; } Where NeuralConnection implements the java.io.Serializable interface. If I do a serialver on MultilayerPerceptron$NeuralEnd I receive the serialVersionUID which I declared. So, why have both JVMs changed this value? Can you help me? Thanks, Alberto

    Read the article

  • How to create a simple adf dashboard application with EJB 3.0

    - by Rodrigues, Raphael
    In this month's Oracle Magazine, Frank Nimphius wrote a very good article about an Oracle ADF Faces dashboard application to support persistent user personalization. You can read this entire article clicking here. The idea in this article is to extend the dashboard application. My idea here is to create a similar dashboard application, but instead ADF BC model layer, I'm intending to use EJB3.0. There are just a one small trick here and I'll show you. I'm using the HR usual oracle schema. The steps are: 1. Create a ADF Fusion Application with EJB as a layer model 2. Generate the entities from table (I'm using Department and Employees only) 3. Create a new Session Bean. I called it: HRSessionEJB 4. Create a new method like that: public List getAllDepartmentsHavingEmployees(){ JpaEntityManager jpaEntityManager = (JpaEntityManager)em.getDelegate(); Query query = jpaEntityManager.createNamedQuery("Departments.allDepartmentsHavingEmployees"); JavaBeanResult.setQueryResultClass(query, AggregatedDepartment.class); return query.getResultList(); } 5. In the Departments entity, create a new native query annotation: @Entity @NamedQueries( { @NamedQuery(name = "Departments.findAll", query = "select o from Departments o") }) @NamedNativeQueries({ @NamedNativeQuery(name="Departments.allDepartmentsHavingEmployees", query = "select e.department_id, d.department_name , sum(e.salary), avg(e.salary) , max(e.salary), min(e.salary) from departments d , employees e where d.department_id = e.department_id group by e.department_id, d.department_name")}) public class Departments implements Serializable {...} 6. Create a new POJO called AggregatedDepartment: package oramag.sample.dashboard.model; import java.io.Serializable; import java.math.BigDecimal; public class AggregatedDepartment implements Serializable{ @SuppressWarnings("compatibility:5167698678781240729") private static final long serialVersionUID = 1L; private BigDecimal departmentId; private String departmentName; private BigDecimal sum; private BigDecimal avg; private BigDecimal max; private BigDecimal min; public AggregatedDepartment() { super(); } public AggregatedDepartment(BigDecimal departmentId, String departmentName, BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min) { super(); this.departmentId = departmentId; this.departmentName = departmentName; this.sum = sum; this.avg = avg; this.max = max; this.min = min; } public void setDepartmentId(BigDecimal departmentId) { this.departmentId = departmentId; } public BigDecimal getDepartmentId() { return departmentId; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getDepartmentName() { return departmentName; } public void setSum(BigDecimal sum) { this.sum = sum; } public BigDecimal getSum() { return sum; } public void setAvg(BigDecimal avg) { this.avg = avg; } public BigDecimal getAvg() { return avg; } public void setMax(BigDecimal max) { this.max = max; } public BigDecimal getMax() { return max; } public void setMin(BigDecimal min) { this.min = min; } public BigDecimal getMin() { return min; } } 7. Create the util java class called JavaBeanResult. The function of this class is to configure a native SQL query to return POJOs in a single line of code using the utility class. Credits: http://onpersistence.blogspot.com.br/2010/07/eclipselink-jpa-native-constructor.html package oramag.sample.dashboard.model.util; /******************************************************************************* * Copyright (c) 2010 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * @author shsmith ******************************************************************************/ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import org.eclipse.persistence.exceptions.ConversionException; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.jpa.JpaHelper; import org.eclipse.persistence.queries.DatabaseQuery; import org.eclipse.persistence.queries.QueryRedirector; import org.eclipse.persistence.sessions.Record; import org.eclipse.persistence.sessions.Session; /*** * This class is a simple query redirector that intercepts the result of a * native query and builds an instance of the specified JavaBean class from each * result row. The order of the selected columns musts match the JavaBean class * constructor arguments order. * * To configure a JavaBeanResult on a native SQL query use: * JavaBeanResult.setQueryResultClass(query, SomeBeanClass.class); * where query is either a JPA SQL Query or native EclipseLink DatabaseQuery. * * @author shsmith * */ public final class JavaBeanResult implements QueryRedirector { private static final long serialVersionUID = 3025874987115503731L; protected Class resultClass; public static void setQueryResultClass(Query query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); DatabaseQuery databaseQuery = JpaHelper.getDatabaseQuery(query); databaseQuery.setRedirector(javaBeanResult); } public static void setQueryResultClass(DatabaseQuery query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); query.setRedirector(javaBeanResult); } protected JavaBeanResult(Class resultClass) { this.resultClass = resultClass; } @SuppressWarnings("unchecked") public Object invokeQuery(DatabaseQuery query, Record arguments, Session session) { List results = new ArrayList(); try { Constructor[] constructors = resultClass.getDeclaredConstructors(); Constructor javaBeanClassConstructor = null; // (Constructor) resultClass.getDeclaredConstructors()[0]; Class[] constructorParameterTypes = null; // javaBeanClassConstructor.getParameterTypes(); List rows = (List) query.execute( (AbstractSession) session, (AbstractRecord) arguments); for (Object[] columns : rows) { boolean found = false; for (Constructor constructor : constructors) { javaBeanClassConstructor = constructor; constructorParameterTypes = javaBeanClassConstructor.getParameterTypes(); if (columns.length == constructorParameterTypes.length) { found = true; break; } // if (columns.length != constructorParameterTypes.length) { // throw new ColumnParameterNumberMismatchException( // resultClass); // } } if (!found) throw new ColumnParameterNumberMismatchException( resultClass); Object[] constructorArgs = new Object[constructorParameterTypes.length]; for (int j = 0; j < columns.length; j++) { Object columnValue = columns[j]; Class parameterType = constructorParameterTypes[j]; // convert the column value to the correct type--if possible constructorArgs[j] = ConversionManager.getDefaultManager() .convertObject(columnValue, parameterType); } results.add(javaBeanClassConstructor.newInstance(constructorArgs)); } } catch (ConversionException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalArgumentException e) { throw new ColumnParameterMismatchException(e); } catch (InstantiationException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalAccessException e) { throw new ColumnParameterMismatchException(e); } catch (InvocationTargetException e) { throw new ColumnParameterMismatchException(e); } return results; } public final class ColumnParameterMismatchException extends RuntimeException { private static final long serialVersionUID = 4752000720859502868L; public ColumnParameterMismatchException(Throwable t) { super( "Exception while processing query results-ensure column order matches constructor parameter order", t); } } public final class ColumnParameterNumberMismatchException extends RuntimeException { private static final long serialVersionUID = 1776794744797667755L; public ColumnParameterNumberMismatchException(Class clazz) { super( "Number of selected columns does not match number of constructor arguments for: " + clazz.getName()); } } } 8. Create the DataControl and a jsf or jspx page 9. Drag allDepartmentsHavingEmployees from DataControl and drop in your page 10. Choose Graph > Type: Bar (Normal) > any layout 11. In the wizard screen, Bars label, adds: sum, avg, max, min. In the X Axis label, adds: departmentName, and click in OK button 12. Run the page, the result is showed below: You can download the workspace here . It was using the latest jdeveloper version 11.1.2.2.

    Read the article

  • Google App Engine JDO how to define class fields ?

    - by Frank
    I have a class like this : import java.io.*; import java.util.*; public class Contact_Info_Entry implements Serializable { public static final long serialVersionUID=26362862L; String Contact_Id,First_Name="",Last_Name="",Company_Name="",Branch_Name="",Address_1="",Address_2="",City="",State="",Zip="",Country="",E_Mail="",Phone; int I_1,I_2; float F_1,F_2; boolean B_1,B_2; GregorianCalendar Date_1, Date_2; Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } If I want to translate it to a class for JDO, do I need to define each field by it self or can I do a group at a time ? For instance do I have to make it like this : @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent public static final long serialVersionUID=26362862L; @Persistent String Contact_Id; @Persistent String First_Name; @Persistent String Last_Name; ...... @Persistent int I_1; @Persistent int I_2; ... @Persistent float F_1; ... @Persistent boolean B_1; @Persistent boolean B_2; @Persistent GregorianCalendar Date_1; ... @Persistent Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Or can I do a group at a time like this : @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent public static final long serialVersionUID=26362862L; @Persistent String Contact_Id,First_Name,Last_Name=""; ...... @Persistent int I_1=0,I_2=1; ... @Persistent float F_1; ... @Persistent boolean B_1,B_2; @Persistent GregorianCalendar Date_1; ... @Persistent Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Or can I skip the "@Persistent" all together like this : import java.io.*; import java.util.*; @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { public static final long serialVersionUID=26362862L; String Contact_Id,First_Name="",Last_Name="",Company_Name="",Branch_Name="",Address_1="",Address_2="",City="",State="",Zip="",Country="", E_Mail="",Phone; int I_1,I_2; float F_1,F_2; boolean B_1,B_2; GregorianCalendar Date_1, Date_2; Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Which are correct ? Frank

    Read the article

  • Google App Engine JDO how to define instance fields ?

    - by Frank
    I have a class like this : import java.io.*; import java.util.*; public class Contact_Info_Entry implements Serializable { public static final long serialVersionUID=26362862L; String Contact_Id,First_Name="",Last_Name="",Company_Name="",Branch_Name="",Address_1="",Address_2="",City="",State="",Zip="",Country="",E_Mail="",Phone; int I_1,I_2; float F_1,F_2; boolean B_1,B_2; GregorianCalendar Date_1, Date_2; Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } If I want to translate it to a class for JDO, do I need to define each field by it self or can I do a group at a time ? For instance do I have to make it like this : @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent public static final long serialVersionUID=26362862L; @Persistent String Contact_Id; @Persistent String First_Name; @Persistent String Last_Name; ...... @Persistent int I_1; @Persistent int I_2; ... @Persistent float F_1; ... @Persistent boolean B_1; @Persistent boolean B_2; @Persistent GregorianCalendar Date_1; ... @Persistent Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Or can I do a group at a time like this : @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent public static final long serialVersionUID=26362862L; @Persistent String Contact_Id,First_Name,Last_Name=""; ...... @Persistent int I_1=0,I_2=1; ... @Persistent float F_1; ... @Persistent boolean B_1,B_2; @Persistent GregorianCalendar Date_1; ... @Persistent Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Or can I skip the "@Persistent" all together like this : import java.io.*; import java.util.*; @PersistenceCapable(identityType=IdentityType.APPLICATION) public class Contact_Info_Entry implements Serializable { public static final long serialVersionUID=26362862L; String Contact_Id,First_Name="",Last_Name="",Company_Name="",Branch_Name="",Address_1="",Address_2="",City="",State="",Zip="",Country="", E_Mail="",Phone; int I_1,I_2; float F_1,F_2; boolean B_1,B_2; GregorianCalendar Date_1, Date_2; Vector<String> A_Vector=new Vector<String>(); public Contact_Info_Entry() { } ...... } Which are correct ? Frank

    Read the article

  • Node Serialization in NetBeans Platform 7.0

    - by Geertjan
    Node serialization makes sense when you're not interested in the data (since that should be serialized to a database), but in the state of the application. For example, when the application restarts, you want the last selected node to automatically be selected again. That's not the kind of information you'll want to store in a database, hence node serialization is not about data serialization but about application state serialization. I've written about this topic in October 2008, here and here, but want to show how to do this again, using NetBeans Platform 7.0. Somewhere I remember reading that this can't be done anymore and that's typically the best motivation for me, i.e., to prove that it can be done after all. Anyway, in a standard POJO/Node/BeanTreeView scenario, do the following: Remove the "@ConvertAsProperties" annotation at the top of the class, which you'll find there if you used the Window Component wizard. We're not going to use property-file based serialization, but plain old java.io.Serializable  instead. In the TopComponent, assuming it is named "UserExplorerTopComponent", typically at the end of the file, add the following: @Override public Object writeReplace() { //We want to work with one selected item only //and thanks to BeanTreeView.setSelectionMode, //only one node can be selected anyway: Handle handle = NodeOp.toHandles(em.getSelectedNodes())[0]; return new ResolvableHelper(handle); } public final static class ResolvableHelper implements Serializable { private static final long serialVersionUID = 1L; public Handle selectedHandle; private ResolvableHelper(Handle selectedHandle) { this.selectedHandle = selectedHandle; } public Object readResolve() { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { try { //Get the TopComponent: UserExplorerTopComponent tc = (UserExplorerTopComponent) WindowManager.getDefault().findTopComponent("UserExplorerTopComponent"); //Get the display text to search for: String selectedDisplayName = selectedHandle.getNode().getDisplayName(); //Get the root, which is the parent of the node we want: Node root = tc.getExplorerManager().getRootContext(); //Find the node, by passing in the root with the display text: Node selectedNode = NodeOp.findPath(root, new String[]{selectedDisplayName}); //Set the explorer manager's selected node: tc.getExplorerManager().setSelectedNodes(new Node[]{selectedNode}); } catch (PropertyVetoException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); return null; } } Assuming you have a node named "UserNode" for a type named "User" containing a property named "type", add the bits in bold below to your "UserNode": public class UserNode extends AbstractNode implements Serializable { static final long serialVersionUID = 1L; public UserNode(User key) { super(Children.LEAF); setName(key.getType()); } @Override public Handle getHandle() { return new CustomHandle(this, getName()); } public class CustomHandle implements Node.Handle { static final long serialVersionUID = 1L; private AbstractNode node = null; private final String searchString; public CustomHandle(AbstractNode node, String searchString) { this.node = node; this.searchString = searchString; } @Override public Node getNode() { node.setName(searchString); return node; } } } Run the application and select one of the user nodes. Close the application. Start it up again. The user node is not automatically selected, in fact, the window does not open, and you will see this in the output: Caused: java.io.InvalidClassException: org.serialization.sample.UserNode; no valid constructor Read this article and then you'll understand the need for this class: public class BaseNode extends AbstractNode { public BaseNode() { super(Children.LEAF); } public BaseNode(Children kids) { super(kids); } public BaseNode(Children kids, Lookup lkp) { super(kids, lkp); } } Now, instead of extending AbstractNode in your UserNode, extend BaseNode. Then the first non-serializable superclass of the UserNode has an explicitly declared no-args constructor, Do the same as the above for each node in the hierarchy that needs to be serialized. If you have multiple nodes needing serialization, you can share the "CustomHandle" inner class above between all the other nodes, while all the other nodes will also need to extend BaseNode (or provide their own non-serializable super class that explicitly declares a no-args constructor). Now, when I run the application, I select a node, then I close the application, restart it, and the previously selected node is automatically selected when the application has restarted.

    Read the article

  • Java - Google App Engine - InvalidClassException when I change a class that was stored in session sc

    - by Spines
    I updated my User class, and now whenever someone that had the old version of the User class stored in their session scope accesses my site, I get an InvalidClassException. javax.servlet.ServletException: java.lang.RuntimeException: java.io.InvalidClassException: User; local class incompatible: stream classdesc serialVersionUID = 4949038118012519093, local class serialVersionUID = -971500502189813151 How do I stop this error from happening for those users? I could probably invalidate everyone's sessions every time I want to update a class that gets stored in session scope, but is there a better way, so that my user's don't have to login again?

    Read the article

  • Hibernate + Spring : cascade deletion ignoring non-nullable constraints

    - by E.Benoît
    Hello, I seem to be having one weird problem with some Hibernate data classes. In a very specific case, deleting an object should fail due to existing, non-nullable relations - however it does not. The strangest part is that a few other classes related to the same definition behave appropriately. I'm using HSQLDB 1.8.0.10, Hibernate 3.5.0 (final) and Spring 3.0.2. The Hibernate properties are set so that batch updates are disabled. The class whose instances are being deleted is: @Entity( name = "users.Credentials" ) @Table( name = "credentials" , schema = "users" ) public class Credentials extends ModelBase { private static final long serialVersionUID = 1L; /* Some basic fields here */ /** Administrator credentials, if any */ @OneToOne( mappedBy = "credentials" , fetch = FetchType.LAZY ) public AdminCredentials adminCredentials; /** Active account data */ @OneToOne( mappedBy = "credentials" , fetch = FetchType.LAZY ) public Account activeAccount; /* Some more reverse relations here */ } (ModelBase is a class that simply declares a Long field named "id" as being automatically generated) The Account class, which is one for which constraints work, looks like this: @Entity( name = "users.Account" ) @Table( name = "accounts" , schema = "users" ) public class Account extends ModelBase { private static final long serialVersionUID = 1L; /** Credentials the account is linked to */ @OneToOne( optional = false ) @JoinColumn( name = "credentials_id" , referencedColumnName = "id" , nullable = false , updatable = false ) public Credentials credentials; /* Some more fields here */ } And here is the AdminCredentials class, for which the constraints are ignored. @Entity( name = "admin.Credentials" ) @Table( name = "admin_credentials" , schema = "admin" ) public class AdminCredentials extends ModelBase { private static final long serialVersionUID = 1L; /** Credentials linked with an administrative account */ @OneToOne( optional = false ) @JoinColumn( name = "credentials_id" , referencedColumnName = "id" , nullable = false , updatable = false ) public Credentials credentials; /* Some more fields here */ } The code that attempts to delete the Credentials instances is: try { if ( account.validationKey != null ) { this.hTemplate.delete( account.validationKey ); } this.hTemplate.delete( account.languageSetting ); this.hTemplate.delete( account ); } catch ( DataIntegrityViolationException e ) { return false; } Where hTemplate is a HibernateTemplate instance provided by Spring, its flush mode having been set to EAGER. In the conditions shown above, the deletion will fail if there is an Account instance that refers to the Credentials instance being deleted, which is the expected behaviour. However, an AdminCredentials instance will be ignored, the deletion will succeed, leaving an invalid AdminCredentials instance behind (trying to refresh that instance causes an error because the Credentials instance no longer exists). I have tried moving the AdminCredentials table from the admin DB schema to the users DB schema. Strangely enough, a deletion-related error is then triggered, but not in the deletion code - it is triggered at the next query involving the table, seemingly ignoring the flush mode setting. I've been trying to understand this for hours and I must admit I'm just as clueless now as I was then.

    Read the article

  • Do Hibernate table classes need to be Serializable?

    - by Scott Leis
    I have inherited a Websphere Portal project that uses Hibernate 3.0 to connect to a SQL Server database. There are about 130 Hibernate table classes in this project. They all implement Serializable. None of them declare a serialVersionUID field, so the Eclipse IDE shows a warning for all of these classes. Is there any actual need for these classes to implement Serializable? If so, is there any tool to add a generated serialVersionUID field to a large number of classes at once (just to make the warnings go away) ?

    Read the article

  • EJB / JSF java.lang.ClassNotFoundException: com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader

    - by Eric Sant'Anna
    I'm in my first time using EJB and JSF, and I can't resolve this: 20:23:12,457 Grave [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8081-2) com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader @439db2b2 (roots: C:\jboss-as-7.1.1.Final\modules)]: java.lang.ClassNotFoundException: com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader @439db2b2 (roots: C:\jboss-as-7.1.1.Final\modules)] I'm getting this when I do an action like a selectOneMenu or a commandButton click. DAOFactory.class @Singleton @Remote(DAOFactoryRemote.class) public class DAOFactory implements DAOFactoryRemote { private static final long serialVersionUID = 6030538139815885895L; @PersistenceContext private EntityManager entityManager; @EJB private JobDAORemote jobDAORemote; /** * Default constructor. */ public DAOFactory() { // TODO Auto-generated constructor stub } @Override public JobDAORemote getJobDAO() { JobDAO jobDAO = (JobDAO) jobDAORemote; jobDAO.setEntityManager(entityManager); return jobDAO; } JobDAO.class @Stateless @Remote(JobDAORemote.class) public class JobDAO implements JobDAORemote { private static final long serialVersionUID = -5483992924812255349L; private EntityManager entityManager; /** * Default constructor. */ public JobDAO() { // TODO Auto-generated constructor stub } @Override public void insert(Job t) { entityManager.persist(t); } @Override public Job findById(Class<Job> classe, Long id) { return entityManager.getReference(classe, id); } @Override public Job findByName(Class<Job> clazz, String name) { return entityManager .createQuery("SELECT job FROM " + clazz.getName() + " job WHERE job.nome = :nome" , Job.class) .setParameter("name", name) .getSingleResult(); } ... TriggerFormBean.class @ManagedBean @ViewScoped @Stateless public class TriggerFormBean implements Serializable { private static final long serialVersionUID = -3293560384606586480L; @EJB private DAOFactoryRemote daoFactory; @EJB private TriggerManagerRemote triggerManagerRemote; ... triggerForm.xhtml (a portion with problem) </p:layoutUnit> <p:layoutUnit id="eastConditionPanel" position="center" size="50%"> <p:panel header="Conditions to Release" style="width:97%;height:97%;"> <h:panelGrid columns="2" cellpadding="3"> <h:outputLabel value="Condition Name:" for="conditionName" /> <p:inputText id="conditionName" value="#{triggerFormBean.newCondition.name}" /> </h:panelGrid> <p:commandButton value="Add Condition" update="conditionsToReleaseList" id="addConditionToRelease" actionListener="#{triggerFormBean.addNewCondition}" /> <p:orderList id="conditionsToReleaseList" value="#{triggerFormBean.trigger.conditionsToRelease}" var="condition" controlsLocation="none" itemLabel="#{condition.name}" itemValue="#{condition}" iconOnly="true" style="width:97%;heigth:97%;"/> </p:panel> </p:layoutUnit> In TriggerFormBean.class if comments daoFactory we get the same exception with triggerManagerRemote, both annotated with @EJB. I'm don't understand the relationship between my DAOFactory and the "Module com.sun.jsf-impl:main"... Thanks.

    Read the article

  • Getting field of type bytea in helper table when using GenerationType.IDENTITY

    - by dtrunk
    I'm creating my db scheme using Hibernate. There's a Table called "tbl_articles" and another one called "tbl_categories". To have a n-n relationship a helper table ("tbl_articles_categories") is needed. Here are all necessary Entities: @Entity @Table( name = "tbl_articles" ) public class Article implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields... public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_categories" ) public class Category implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_articles_categories" ) @AssociationOverrides({ @AssociationOverride( name = "pk.article", joinColumns = @JoinColumn( name = "article_id" ) ), @AssociationOverride( name = "pk.category", joinColumns = @JoinColumn( name = "category_id" ) ) }) public class ArticleCategory { private ArticleCategoryPK pk = new ArticleCategoryPK(); public void setPk( ArticleCategoryPK pk ) { this.pk = pk; } @EmbeddedId public ArticleCategoryPK getPk() { return pk; } @Transient public Article getArticle() { return pk.getArticle(); } public void setArticle( Article article ) { pk.setArticle( article ); } @Transient public Category getCategory() { return pk.getCategory(); } public void setCategory( Category category ) { pk.setCategory( category ); } } @Embeddable public class ArticleCategoryPK implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_article_id" ) private Article article; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_category_id" ) private Category category; public ArticleCategoryPK( Article article, Category category ) { setArticle( article ); setCategory( category ); } public ArticleCategoryPK() { } public Article getArticle() { return article; } public void setArticle( Article article ) { this.article = article; } public Category getCategory() { return category; } public void setCategory( Category category ) { this.category = category; } } Now, I'm getting a serial type what I wanted in my articles table as well as in my categories table. But looking into my helper table, there aren't the expected fields article_id and category_id each of type integer - instead there are article and category of type bytea. What's wrong here? EDIT: Sorry, forgot to mention that I'm using PostgreSQL.

    Read the article

  • Compass - Lucene Full text search. Structure and Best Practice.

    - by Rob
    Hi, I have played about with the tutorial and Compass itself for a bit now. I have just started to ramp up the use of it and have found that the performance slows drastically. I am certain that this is due to my mappings and the relationships that I have between entities and was looking for suggestions about how this should be best done. Also as a side question I wanted to know if a variable is in an @searchableComponent but is not defined as @searchable when the component object is pulled out of Compass results will you be able to access that variable? I have 3 main classes that I want to search on - Provider, Location and Activity. They are all inter-related - a Provider can have many locations and activites and has an address; A Location has 1 provider, many activities and an address; An activity has 1 provider and many locations. I have a join table between activity and Location called ActivityLocation that can later provider additional information about the relationship. My classes are mapped to compass as shown below for provider location activity and address. This works but gives a huge index and searches on it are comparatively slow, any advice would be great. Cheers, Rob @Searchable public class AbstractActivity extends LightEntity implements Serializable { /** * Serialisation ID */ private static final long serialVersionUID = 3445339493203407152L; @SearchableId (name="actID") private Integer activityId =-1; @SearchableComponent() private Provider provider; @SearchableComponent(prefix = "activity") private Category category; private String status; @SearchableProperty (name = "activityName") @SearchableMetaData (name = "activityshortactivityName") private String activityName; @SearchableProperty (name = "shortDescription") @SearchableMetaData (name = "activityshortDescription") private String shortDescription; @SearchableProperty (name = "abRating") @SearchableMetaData (name = "activityabRating") private Integer abRating; private String contactName; private String phoneNumber; private String faxNumber; private String email; private String url; @SearchableProperty (name = "completed") @SearchableMetaData (name = "activitycompleted") private Boolean completed= false; @SearchableProperty (name = "isprivate") @SearchableMetaData (name = "activityisprivate") private Boolean isprivate= false; private Boolean subs= false; private Boolean newsfeed= true; private Set news = new HashSet(0); private Set ActivitySession = new HashSet(0); private Set payments = new HashSet(0); private Set userclub = new HashSet(0); private Set ActivityOpeningTimes = new HashSet(0); private Set Events = new HashSet(0); private User creator; private Set userInterested = new HashSet(0); boolean freeEdit = false; private Integer activityType =0; @SearchableComponent (maxDepth=2) private Set activityLocations = new HashSet(0); private Double userRating = -1.00; Getters and Setters .... @Searchable public class AbstractLocation extends LightEntity implements Serializable { /** * Serialisation ID */ private static final long serialVersionUID = 3445339493203407152L; @SearchableId (name="locationID") private Integer locationId; @SearchableComponent (prefix = "location") private Category category; @SearchableComponent (maxDepth=1) private Provider provider; @SearchableProperty (name = "status") @SearchableMetaData (name = "locationstatus") private String status; @SearchableProperty private String locationName; @SearchableProperty (name = "shortDescription") @SearchableMetaData (name = "locationshortDescription") private String shortDescription; @SearchableProperty (name = "abRating") @SearchableMetaData (name = "locationabRating") private Integer abRating; private Integer boolUseProviderDetails; @SearchableProperty (name = "contactName") @SearchableMetaData (name = "locationcontactName") private String contactName; @SearchableComponent private Address address; @SearchableProperty (name = "phoneNumber") @SearchableMetaData (name = "locationphoneNumber") private String phoneNumber; @SearchableProperty (name = "faxNumber") @SearchableMetaData (name = "locationfaxNumber") private String faxNumber; @SearchableProperty (name = "email") @SearchableMetaData (name = "locationemail") private String email; @SearchableProperty (name = "url") @SearchableMetaData (name = "locationurl") private String url; @SearchableProperty (name = "completed") @SearchableMetaData (name = "locationcompleted") private Boolean completed= false; @SearchableProperty (name = "isprivate") @SearchableMetaData (name = "locationisprivate") private Boolean isprivate= false; @SearchableComponent private Set activityLocations = new HashSet(0); private Set LocationOpeningTimes = new HashSet(0); private Set events = new HashSet(0); @SearchableProperty (name = "adult_cost") @SearchableMetaData (name = "locationadult_cost") private String adult_cost =""; @SearchableProperty (name = "child_cost") @SearchableMetaData (name = "locationchild_cost") private String child_cost =""; @SearchableProperty (name = "family_cost") @SearchableMetaData (name = "locationfamily_cost") private String family_cost =""; private Double userRating = -1.00; private Set costs = new HashSet(0); private String cost_caveats =""; Getters and Setters .... @Searchable public class AbstractActivitylocations implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1365110541466870626L; @SearchableId (name="id") private Integer id; @SearchableComponent private Activity activity; @SearchableComponent private Location location; Getters and Setters..... @Searchable public class AbstractProvider extends LightEntity implements Serializable { private static final long serialVersionUID = 3060354043429663058L; @SearchableId private Integer providerId = -1; @SearchableComponent (prefix = "provider") private Category category; @SearchableProperty (name = "businessName") @SearchableMetaData (name = "providerbusinessName") private String businessName; @SearchableProperty (name = "contactName") @SearchableMetaData (name = "providercontactName") private String contactName; @SearchableComponent private Address address; @SearchableProperty (name = "phoneNumber") @SearchableMetaData (name = "providerphoneNumber") private String phoneNumber; @SearchableProperty (name = "faxNumber") @SearchableMetaData (name = "providerfaxNumber") private String faxNumber; @SearchableProperty (name = "email") @SearchableMetaData (name = "provideremail") private String email; @SearchableProperty (name = "url") @SearchableMetaData (name = "providerurl") private String url; @SearchableProperty (name = "status") @SearchableMetaData (name = "providerstatus") private String status; @SearchableProperty (name = "notes") @SearchableMetaData (name = "providernotes") private String notes; @SearchableProperty (name = "shortDescription") @SearchableMetaData (name = "providershortDescription") private String shortDescription; private Boolean completed = false; private Boolean isprivate = false; private Double userRating = -1.00; private Integer ABRating = 1; @SearchableComponent private Set locations = new HashSet(0); @SearchableComponent private Set activities = new HashSet(0); private Set ProviderOpeningTimes = new HashSet(0); private User creator; boolean freeEdit = false; Getters and Setters... Thanks for reading!! Rob

    Read the article

  • Hibernate Auto-Increment Setup

    - by dharga
    How do I define an entity for the following table. I've got something that isn't working and I just want to see what I'm supposed to do. USE [BAMPI_TP_dev] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[MemberSelectedOptions]( [OptionId] [int] NOT NULL, [SeqNo] [smallint] IDENTITY(1,1) NOT NULL, [OptionStatusCd] [char](1) NULL ) ON [PRIMARY] GO SET ANSI_PADDING OFF This is what I have already that isn't working. @Entity @Table(schema="dbo", name="MemberSelectedOptions") public class MemberSelectedOption extends BampiEntity implements Serializable { @Embeddable public static class MSOPK implements Serializable { private static final long serialVersionUID = 1L; @Column(name="OptionId") int optionId; @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="SeqNo", unique=true, nullable=false) BigDecimal seqNo; //Getters and setters here... } private static final long serialVersionUID = 1L; @EmbeddedId MSOPK pk = new MSOPK(); @Column(name="OptionStatusCd") String optionStatusCd; //More Getters and setters here... } I get the following ST. [5/25/10 15:49:40:221 EDT] 0000003d JDBCException E org.slf4j.impl.JCLLoggerAdapter error Cannot insert explicit value for identity column in table 'MemberSelectedOptions' when IDENTITY_INSERT is set to OFF. [5/25/10 15:49:40:221 EDT] 0000003d AbstractFlush E org.slf4j.impl.JCLLoggerAdapter error Could not synchronize database state with session org.hibernate.exception.SQLGrammarException: could not insert: [com.bob.proj.ws.model.MemberSelectedOption] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2285) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at com.bcbst.bamp.ws.dao.MemberSelectedOptionDAOImpl.saveMemberSelectedOption(MemberSelectedOptionDAOImpl.java:143) at com.bcbst.bamp.ws.common.AlertReminder.saveMemberSelectedOptions(AlertReminder.java:76) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    Read the article

  • Lost with hibernate - OneToMany resulting in the one being pulled back many times..

    - by Andy
    I have this DB design: CREATE TABLE report ( ID MEDIUMINT PRIMARY KEY NOT NULL AUTO_INCREMENT, user MEDIUMINT NOT NULL, created TIMESTAMP NOT NULL, state INT NOT NULL, FOREIGN KEY (user) REFERENCES user(ID) ON UPDATE CASCADE ON DELETE CASCADE ); CREATE TABLE reportProperties ( ID MEDIUMINT NOT NULL, k VARCHAR(128) NOT NULL, v TEXT NOT NULL, PRIMARY KEY( ID, k ), FOREIGN KEY (ID) REFERENCES report(ID) ON UPDATE CASCADE ON DELETE CASCADE ); and this Hibernate Markup: @Table(name="report") @Entity(name="ReportEntity") public class ReportEntity extends Report{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Integer ID; @Column(name="user") private Integer user; @Column(name="created") private Timestamp created; @Column(name="state") private Integer state = ReportState.RUNNING.getLevel(); @OneToMany(mappedBy="pk.ID", fetch=FetchType.EAGER) @JoinColumns( @JoinColumn(name="ID", referencedColumnName="ID") ) @MapKey(name="pk.key") private Map<String, ReportPropertyEntity> reportProperties = new HashMap<String, ReportPropertyEntity>(); } and @Table(name="reportProperties") @Entity(name="ReportPropertyEntity") public class ReportPropertyEntity extends ReportProperty{ @Embeddable public static class ReportPropertyEntityPk implements Serializable{ /** * long#serialVersionUID */ private static final long serialVersionUID = 2545373078182672152L; @Column(name="ID") protected int ID; @Column(name="k") protected String key; } @EmbeddedId protected ReportPropertyEntityPk pk = new ReportPropertyEntityPk(); @Column(name="v") protected String value; } And i have inserted on Report and 4 Properties for that report. Now when i execute this: this.findByCriteria( Order.asc("created"), Restrictions.eq("user", user.getObject(UserField.ID)) ) ); I get back the report 4 times, instead of just the once with a Map with the 4 properties in. I'm not great at Hibernate to be honest, prefer straight SQL but I must learn, but i can't see what it is that is wrong.....? Any suggestions?

    Read the article

  • EJB and JPA and @OneToMany - Transaction too long?

    - by marioErr
    Hello. I'm using EJB and JPA, and when I try to access PhoneNumber objects in phoneNumbers attribute of Contact contact, it sometimes take several minutes for it to actually return data. It just returns no phoneNumbers, not even null, and then, after some time, when i call it again, it magically appears. This is how I access data: for (Contact c : contactFacade.findAll()) { System.out.print(c.getName()+" "+c.getSurname()+" : "); for (PhoneNumber pn : c.getPhoneNumbers()) { System.out.print(pn.getNumber()+" ("+pn.getDescription()+"); "); } } I'm using facade session ejb generated by netbeans (basic CRUD methods). It always prints correct name and surname, phonenumbers and description are only printed after some time (it varies) from creating it via facade. I'm guessing it has something to do with transactions. How to solve this? These are my JPA entities: contact @Entity public class Contact implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String surname; @OneToMany(cascade = CascadeType.REMOVE, mappedBy = "contact") private Collection<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(); phonenumber @Entity public class PhoneNumber implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String number; private String description; @ManyToOne() @JoinColumn(name="CONTACT_ID") private Contact contact;

    Read the article

  • Hibernate Transient Extends problem

    - by mrvreddy
    @MappedSuperclass public abstract class BaseAbstract implements Serializable{ private static final long serialVersionUID = 1L; protected String test = //some random value; public String getTest() { return test; } public void setTest(String test){ this.test = test; } } @Entity public class Artist extends BaseAbstract { private static final long serialVersionUID = 1L; private Integer id; @override @Transient public String getTest() { return test; } ..... } My question is... when i am trying to do any operation on the artist, along with id and name, test is also getting saved which should not be the case... if i add the same transient on the baseabstract class getTest() method, i see test column NOT getting created(ideally what it should happen) but if i try to override the method with adding annotaion in the sub class it creates the test column... I dont know why this is happening since when hibernate is creating the artist object and checks for annotations, it should see the transient annotation present on the getTest() of artist method...and should not create a column in the database... Let me know if you need any clarification.... Any response on this is greatly appreciated.... Thank you

    Read the article

  • Accessing Application Scoped Bean Causes NullPointerException

    - by user2946861
    What is an Application Scoped Bean? I understand it to be a bean which will exist for the life of the application, but that doesn't appear to be the correct interpretation. I have an application which creates an application scoped bean on startup (eager=true) and then a session bean that tries to access the application scoped bean's objects (which are also application scoped). But when I try to access the application scoped bean from the session scoped bean, I get a null pointer exception. Here's excerpts from my code: Application Scoped Bean: @ManagedBean(eager=true) @ApplicationScoped public class Bean1 implements Serializable{ private static final long serialVersionUID = 12345L; protected ArrayList<App> apps; // construct apps so they are available for the session scoped bean // do time consuming stuff... // getters + setters Session Scoped Bean: @ManagedBean @SessionScoped public class Bean2 implements Serializable{ private static final long serialVersionUID = 123L; @Inject private Bean1 bean1; private ArrayList<App> apps = bean1.getApps(); // null pointer exception What appears to be happening is, Bean1 is created, does it's stuff, then is destroyed before Bean2 can access it. I was hoping using application scoped would keep Bean1 around until the container was shutdown, or the application was killed, but this doesn't appear to be the case.

    Read the article

  • Could not synchronize database state with session

    - by user359427
    Hello all, I'm having trouble trying to persist an entity which ID is a generated value. This entity (A), at persistence time, has to persist in cascade another entity(B). The relationship within A and B is OneToMany, and the property related in B is part of a composite key. I'm using Eclipse, JBOSS Runtime, JPA/Hibernate Here is my code: Entity A: @Entity public class Cambios implements Serializable { private static final long serialVersionUID = 1L; @SequenceGenerator(name="CAMBIOS_GEN",sequenceName="CAMBIOS_SEQ",allocationSize=1) @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CAMBIOS_GEN") @Column(name="ID_CAMBIO") private Long idCambio; //bi-directional many-to-one association to ObjetosCambio @OneToMany(cascade={CascadeType.PERSIST},mappedBy="cambios") private List<ObjetosCambio> objetosCambioList; public Cambios() { } ... } Entity B: @Entity @Table(name="OBJETOS_CAMBIO") public class ObjetosCambio implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private ObjetosCambioPK id; //bi-directional many-to-one association to Cambios @ManyToOne @JoinColumn(name="ID_CAMBIO", insertable=false, updatable=false) private Cambios cambios; //bi-directional many-to-one association to Objetos @ManyToOne @JoinColumn(name="ID_OBJETO", insertable=false, updatable=false) private Objetos objetos; public ObjetosCambio() { } ... Entity B PK: @Embeddable public class ObjetosCambioPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @Column(name="ID_OBJETO") private Long idObjeto; @Column(name="ID_CAMBIO") private Long idCambio; public ObjetosCambioPK() { } Client: public String generarCambio(){ ServiceLocator serviceLocator = null; try { serviceLocator = serviceLocator.getInstance(); FachadaLocal tcLocal; tcLocal = (FachadaLocal)serviceLocator.getFacadeService("java:comp/env/negocio/Fachada"); Cambios cambio = new Cambios(); Iterator it = objetosLocal.iterator(); //OBJETOSLOCAL IS ALREADY POPULATED OUTSIDE OF THIS METHOD List<ObjetosCambio> ocList = new ArrayList(); while (it.hasNext()){ Objetos objeto = (Objetos)it.next(); ObjetosCambio objetosCambio = new ObjetosCambio(); objetosCambio.setCambios(cambio); //AT THIS TIME THIS "CAMBIO" DOES NOT HAVE ITS ID, ITS SUPPOSED TO BE GENERATED AT PERSISTENCE TIME ObjetosCambioPK ocPK = new ObjetosCambioPK(); ocPK.setIdObjeto(objeto.getIdObjeto()); objetosCambio.setId(ocPK); ocList.add(objetosCambio); } cambio.setObjetosCambioList(ocList); tcLocal.persistEntity(cambio); return "exito"; } catch (NamingException e) { // TODO e.printStackTrace(); } return null; } ERROR: 15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000 15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") 15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000 15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") 15:23:25,717 ERROR [AbstractFlushingEventListener] Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.ejb.AbstractEntityManagerImpl$1.beforeCompletion(AbstractEntityManagerImpl.java:504) at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:101) at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:269) at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:89) at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:177) at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1423) at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:137) at com.arjuna.ats.jbossatx.BaseTransactionManagerDelegate.commit(BaseTransactionManagerDelegate.java:75) at org.jboss.aspects.tx.TxPolicy.endTransaction(TxPolicy.java:170) at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:87) at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:190) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:76) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.tx.NullInterceptor.invoke(NullInterceptor.java:42) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.security.Ejb3AuthenticationInterceptorv2.invoke(Ejb3AuthenticationInterceptorv2.java:186) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:41) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.BlockContainerShutdownInterceptor.invoke(BlockContainerShutdownInterceptor.java:67) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.aspects.currentinvocation.CurrentInvocationInterceptor.invoke(CurrentInvocationInterceptor.java:67) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.session.SessionSpecContainer.invoke(SessionSpecContainer.java:176) at org.jboss.ejb3.session.SessionSpecContainer.invoke(SessionSpecContainer.java:216) at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:207) at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:164) at $Proxy298.persistEntity(Unknown Source) at backing.SolicitudCambio.generarCambio(SolicitudCambio.java:521) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:146) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:92) at javax.faces.component.UICommand.broadcast(UICommand.java:332) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:287) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:401) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:95) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:245) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:110) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:213) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:301) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.BatchUpdateException: ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") Thanks in advance! JM.-

    Read the article

  • Page expired issue with back button and wicket SortableDataProvider and DataTable

    - by David
    Hi, I've got an issue with SortableDataProvider and DataTable in wicket. I've defined my DataTable as such: IColumn<Column>[] columns = new IColumn[9]; //column values are mapped to the private attributes listed in ColumnImpl.java columns[0] = new PropertyColumn(new Model("#"), "columnPosition", "columnPosition"); columns[1] = new PropertyColumn(new Model("Description"), "description"); columns[2] = new PropertyColumn(new Model("Type"), "dataType", "dataType"); Adding it to the table: DataTable<Column> dataTable = new DataTable<Column>("columnsTable", columns, provider, maxRowsPerPage) { @Override protected Item<Column> newRowItem(String id, int index, IModel<Column> model) { return new OddEvenItem<Column>(id, index, model); } }; My data provider: public class ColumnSortableDataProvider extends SortableDataProvider<Column> { private static final long serialVersionUID = 1L; private List list = null; public ColumnSortableDataProvider(Table table, String sortProperty) { this.list = Arrays.asList(table.getColumns().toArray(new Column[0])); setSort(sortProperty, true); } public ColumnSortableDataProvider(List list, String sortProperty) { this.list = list; setSort(sortProperty, true); } @Override public Iterator iterator(int first, int count) { /* first - first row of data count - minimum number of elements to retrieve So this method returns an iterator capable of iterating over {first, first+count} items */ Iterator iterator = null; try { if(getSort() != null) { Collections.sort(list, new Comparator() { private static final long serialVersionUID = 1L; @Override public int compare(Column c1, Column c2) { int result=1; PropertyModel<Comparable> model1= new PropertyModel<Comparable>(c1, getSort().getProperty()); PropertyModel<Comparable> model2= new PropertyModel<Comparable>(c2, getSort().getProperty()); if(model1.getObject() == null && model2.getObject() == null) result = 0; else if(model1.getObject() == null) result = 1; else if(model2.getObject() == null) result = -1; else result = ((Comparable)model1.getObject()).compareTo(model2.getObject()); result = getSort().isAscending() ? result : -result; return result; } }); } if (list.size() (first+count)) iterator = list.subList(first, first+count).iterator(); else iterator = list.iterator(); } catch (Exception e) { e.printStackTrace(); } return iterator; } The problem is the following: - I click a column header to sort by that column. - I navigate to a different page - I click Back (or Forward if I do the opposite scenario) - Page has expired. It'd be nice to generate the page using PageParameters but I somehow need to intercept the sort event to do so. Any pointers would be greatly appreciated. Thanks a ton!! David

    Read the article

  • Spring MVC return ajax response using Jackson

    - by anshumn
    I have a scenario where I am filling a dropdown box in JSP through AJAX response from the server. In the controller, I am retuning a Collection of Product objects and have annotated the return type with @ResponseBody. Controller - @RequestMapping(value="/getServicesForMarket", method = RequestMethod.GET) public @ResponseBody Collection<Product> getServices(@RequestParam(value="marketId", required=true) int marketId) { Collection<Product> products = marketService.getProducts(marketId); return products; } And Product is @Entity @Table(name = "PRODUCT") public class Product implements Serializable { private static final long serialVersionUID = 1L; private int id; private Market market; private Service service; private int price; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "MARKET_ID") public Market getMarket() { return market; } public void setMarket(Market market) { this.market = market; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "SERVICE_ID") public Service getService() { return service; } public void setService(Service service) { this.service = service; } @Column(name = "PRICE") public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } Service is @Entity @Table(name="SERVICE") public class Service implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private String description; @Id @GeneratedValue @Column(name="ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="DESCRIPTION") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } In the JSP, I need to get the data from the service field of Product also. So I in my JQuery callback function, I have written like product.service.description to get the data. It seems that by default Jackson is not mapping the associated service object (or any other custom object). Also I am not getting any exception. In the JSP, I do not get the data. It is working fine when I return Collection of some object which does not contain any other custom objects as its fields. Am I missing any settings for this to work? Thanks!

    Read the article

1 2 3 4 5 6  | Next Page >