JPA GenerationType.IDENTITY

Hello,
is there any way how to persuade Toplink Essentials to use SCOPE_IDENTITY() instead of @@IDENTITY for returning identity vaues of newly inserted (persisted) objects?
My problem is that the target table on MS SQL server has insert trigger which inserts records to another table. Thus @@IDENTITY returns wrong value.
Thanks for any advice.
Pavel Zelenka

Thanks. I presume it requires EclpseLink. However I switched JPA provider to EclipseLink
made new classs
public class MySQLServerPlatform extends SQLServerPlatform {
@Override
public ValueReadQuery buildSelectQueryForIdentity() {
ValueReadQuery valueReadQuery = new ValueReadQuery("select scope_identity()");
return valueReadQuery;
added <property name="eclipselink.target-database" value="cz.mediaservis.metro.entity.MySQLServerPlatform"/> to persistence.xml
and after persisting I got exception
Exception [EclipseLink-4011] (Eclipse Persistence Services - 1.1.0.r3634): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
Probably I did something wrong. Could you plese help?
Thx

Similar Messages

  • Toplink Essentials JPA doesn't use GenerationType.IDENTITY

    Based on EJB 3 and JPA I want to store some entities (@Entity) in a database. For some of those entites the database auto increments the primary key. In these cases I defined a @TableGenerator and a @GeneratedValue using GenerationType.IDENTITY as strategy in order to get the primary key (@Id) updated after the entity has been persisted.
    Short example:
    @Entity
    @Table(name = "orders")
    public class POrder implements PEntity {
         @TableGenerator(name = "orderIdGenerator", initialValue = 0, allocationSize = 1)
         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "orderIdGenerator")
         @Column(name = "orderNumber", nullable = false)
         private Integer orderNumber;
    ...I am running the application on GlassFish. I added a corresponding JDBC resource to the server configuration, using the specific MySql driver interfaces.
    Persisting entities which doesn't use a TableGenerator works, but as soon as I try to persist an entity which should use a TableGenerator I am running in the following exception:
    beergame.server.exception.BeergameServerException: nested exception is: Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b55-fcs (10/10/2008))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'beergame3.sequence' doesn't exist
    Error Code: 1146
    Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
         bind => [1, roleIdGenerator]
    Query: DataModifyQuery()
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b55-fcs (10/10/2008))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'beergame3.sequence' doesn't exist
    Error Code: 1146
    Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
         bind => [1, roleIdGenerator]
    Query: DataModifyQuery()
         at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:311)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:654)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:703)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:492)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:452)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeCall(AbstractSession.java:690)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:214)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:257)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:237)
         at oracle.toplink.essentials.queryframework.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:86)
         at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:628)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:1845)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:952)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:924)
         at oracle.toplink.essentials.sequencing.QuerySequence.update(QuerySequence.java:344)
         at oracle.toplink.essentials.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:283)
         at oracle.toplink.essentials.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:96)
         at oracle.toplink.essentials.sequencing.Sequence.getGeneratedVector(Sequence.java:281)
         at oracle.toplink.essentials.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:420)
         at oracle.toplink.essentials.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:846)
         at oracle.toplink.essentials.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:110)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:240)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:355)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3266)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:432)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3226)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:221)
         at com.sun.enterprise.util.EntityManagerWrapper.persist(EntityManagerWrapper.java:440)
         at beergame.server.model.trans.impl.TExtensionOfPEntityImpl.persist(TExtensionOfPEntityImpl.java:130)
         at beergame.server.model.trans.impl.TRoleImpl.<init>(TRoleImpl.java:61)
         at beergame.server.logic.trans.impl.GameLogicImpl.assignUserToValueChainLevel(GameLogicImpl.java:81)
         at beergame.server.logic.remote.impl.UserSessionBean.createGame(UserSessionBean.java:65)
    I wonder why a sequence table has to be update whereas IDENTITY is defined as strategy. I tried also AUTO as strategy but it doesn' matter, the result is the same.
    I read several posts in forums, but couldn't find a solution. So I still have no idea how to get IDENTITY used as strategy. Any one of you does?
    My configuration:
    IDE: Eclipse 3.4.0
    Server: GlassFish V2 Java EE 5
    JPA Implementation: Toplink Essentials v2.1-b55
    JPA driver: oracle.toplink.essentials.PersistenceProvider
    Database: MySQL 5.0.51a
    JDBC driver: mysql-connector-java-5.1.5

    I did it. I must admit, I was a little bit confused by the annotation TableGenerator. It is not responsible for generating ids of a table at all but only in conjunction with a table which should provide ids.
    After I removed @TableGenerator and also the corresponding reference within @GeneratedValue the persistence works as expected. Now the code looks like this:
    @Entity
    @Table(name = "orders")
    public class POrder implements PEntity {
         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)
         @Column(name = "orderNumber", nullable = false)
         private Integer orderNumber;
    ...Edited by: TomCat78 on Oct 12, 2008 3:38 PM

  • JPA cascade with  @GeneratedValue(strategy=GenerationType.IDENTITY)

    If anyone has got cascading persistance working in JPA with database generated primary keys I'd be much obliged if you could let me know how.
    Am attempting to use tables with database auto generated primary keys (MySQL AUTO_INCREMENT), and using the JPA cascade features. But I can't see how to make it work.
    The problem is that if you cascade persist a series of entities, you need to know the database primary keys before you persist to the database.
    If I remove all the cascades in my @entity's, and explicitly persist entities in the correct order so the primary keys are set before them being needed, then all is ok.
    When I put the cascades in, my JPA implementation (Toplink) attempts to create the entities with foreign keys to tables with the yet to be generated primary keys all null. I was hoping JPA/Toplink would be clever enough to persist the entities in order, setting the database generated primary keys as it went.
    Has anyone tried this in Hibernate?
    Sampe code exerts that does not work:
    @Entity
    public class Address implements Serializable {
       private long id;
       private Collection<Contact> contacts = new ArrayList<Contact>();
       @OneToMany(cascade = { CascadeType.ALL })
       public Collection<Contact> getContacts() {
          return contacts;
    @Entity
    public class Contact implements Serializable {
       private long id;
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
    CREATE TABLE address (
           id BIGINT NOT NULL AUTO_INCREMENT
         , address_line_1 VARCHAR(64)
         , address_line_2 VARCHAR(64)
         , address_line_3 VARCHAR(64)
         , suburb VARCHAR(64)
         , postcode VARCHAR(16)
         , state VARCHAR(64)
         , country_code CHAR(2)
         , PRIMARY KEY (id)
    CREATE TABLE contact (
           id BIGINT NOT NULL AUTO_INCREMENT
         , address_id BIGINT
         , contact_type CHAR(10)
         , value VARCHAR(255)
         , PRIMARY KEY (id)
         , INDEX (address_id)
         , CONSTRAINT FK_contact_address FOREIGN KEY (address_id)
                      REFERENCES address (id)
    );

    The way I have it, the contact does need annotations as it is a bidirectional link. The contact defines the link and the address has a mappedBy="address".
    If you remove the annotations on contact, I think you will need to set up a unidirectional one-to-many link and my 'text book' says you need to have a join table to implement this. I tried all kinds of ways to have a unidirectional one-to-many link without a join table, but never succeeded.
    I found if a persist failed it would still use up sequence numbers (Hibernate and MySQL), but I did not come accross your problem. I found it useful to look on the SQL Database logs to see exactly what SQL was getting to the server.
    My code - so far working fine, am in mid development though.
    Address.java:
    @Entity
    @Table(name = "address", schema = "z")
    public class Address implements Serializable {
       private static final long serialVersionUID = 1L;
       private long id;
       private String addressLine1;
       private Collection<Contact> contacts = new ArrayList<Contact>();
       public Address() {
          super();
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
       public void setId(long id) {
          this.id = id;
       @Column(name = "address_line_1")
       public String getAddressLine1() {
          return this.addressLine1;
       public void setAddressLine1(String addressLine1) {
          this.addressLine1 = addressLine1;
       @OneToMany(mappedBy="address", cascade={CascadeType.ALL})
       public Collection<Contact> getContacts() {
          return contacts;
       public void setContacts(Collection<Contact> contacts) {
          this.contacts = contacts;
    Contact.java:
    @Entity
    @Table(name = "contact", schema = "z")
    public class Contact implements Serializable {
       private static final long serialVersionUID = 1L;
       private long id;
       private Address address;
       private String value;
       private String contactType;
       public Contact() {
          super();
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
       public void setId(long id) {
          this.id = id;
       @ManyToOne (cascade={CascadeType.ALL})
       @JoinColumn(name="address_id", referencedColumnName="id", nullable=false, updatable=false)
       public Address getAddress() {
          return this.address;
       public void setAddress(Address address) {
          this.address = address;
       public String getValue() {
          return this.value;
       public void setValue(String value) {
          this.value = value;
       @Column(name = "contact_type")
       public String getContactType() {
          return this.contactType;
       public void setContactType(String contactType) {
          this.contactType = contactType;
    }

  • Problem with JPA Implementations and SQL BIGINT in primary keys

    I have a general Question about the mapping of the SQL datatype BIGINT. I discovered, that there are some different behaviour depending on the JPA implementation. I tested with TopLink Essentials (working) and with Hibernate (not working).
    Here is the case:
    Table definition:
    /*==============================================================*/
    /* Table: CmdQueueIn */
    /*==============================================================*/
    create table MTRACKER.CmdQueueIn
    CmdQueueInId bigint not null global autoincrement,
    Type int,
    Cmd varchar(2048),
    CmdState int,
    MLUser bigint not null,
    ExecutionTime timestamp,
    FinishTime timestamp,
    ExecutionServer varchar(64),
    ScheduleString varchar(64),
    RetryCount int,
    ResultMessage varchar(256),
    RecordState int not null default 1,
    CDate timestamp not null default current timestamp,
    MDate timestamp not null default current timestamp,
    constraint PK_CMDQUEUEIN primary key (CmdQueueInId)
    The java class for this table has the following annotation for the primary key field:
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "CmdQueueInId", nullable = false)
    private BigInteger cmdQueueInId;
    When using hibernate 3.2.1 as JPA provider I get the following exception:
    avax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:629)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:218)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:176)
    at $Proxy16.persist(Unknown Source)
    at com.trixpert.dao.CmdQueueInDAO.save(CmdQueueInDAO.java:46)
    at com.trixpert.test.dao.CmdQueueInDAOTest.testCreateNewCmd(CmdQueueInDAOTest.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at junit.framework.TestCase.runTest(TestCase.java:154)
    at junit.framework.TestCase.runBare(TestCase.java:127)
    at
    Caused by: org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
    at org.hibernate.id.IdentifierGeneratorFactory.get(IdentifierGeneratorFactory.java:59)
    at org.hibernate.id.IdentifierGeneratorFactory.getGeneratedIdentity(IdentifierGeneratorFactory.java:35)
    at org.hibernate.id.IdentityGenerator$BasicDelegate.getResult(IdentityGenerator.java:157)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2108)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2588)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
    at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
    at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
    ... 34 more
    This means, that their ID generator does not support java.math.BigInteger as datatype.
    But the code works if I take TopLink essentials as JPA Provider.
    Looking at the spec shows the following:
    In chapter 2.1.4 "If generated primary keys are used, only integral types will be portable." Integral datatypes are byte, short, int, long and char. This would mean, that the Hibernate implementation fits the spec but there seem to be a problem in general with BIGINT datatypes.
    I use a SYBASE database. There it is possible to declare a UNSIGNED BIGINT. The range of numbers is therefore 0 - 2^64 - 1. Since in Java a long is always signed it would mean its range is from -2^63 -1 to 2^63 -1. So a mapping of BIGINT to java.lang.long could result in an overflow.
    The interesting thing is, that I used NetBeans to reverse engineer an existing database schema. It generated for all Primary Keys of Type BIGINT automatically a java.math.BigInteger. But for other fields (not being keys) it mapped BIGINTs to java.lang.long.
    It looks like there are some problems with either the spec itself or the implementation of it. While TopLink seems to handle the problem correctly, Hibernate doesn't. But Hibernate seems to fulfill the spec.
    Is anybody familiar with the Spec reading this and can elaborate a little about this situation?
    Many thanks for your input and feedback.
    Tom

    Not sure if I clearly understand your issue, would be good if you can explain it a bit more clearly.
    "I select a value from LOV and this value don't refresh in the view"
    If you mean ViewObject, check if autoSubmit property is set to true.
    Amit

  • SAP JPA and lazy loading

    Dear experts,
      I have a WD application with EJB model. I have faced strange JPA exception (I am using SAP JPA implementation).
      This is 2 Entities with relationship
    @Entity
    @Table( schema = "dbo", name = "class")
    public class ClassEntity {
      private Long id;
            @Id
         @Column(name="id")
         @GeneratedValue(strategy= GenerationType.IDENTITY)
        public Long getId() {
              return id;
         public void setId(Long id) {
              this.id = id;
    private Collection<ClassAttributeEntity> classAttributesById;
        @OneToMany(mappedBy = "classByClassId", fetch=FetchType.LAZY)
        public Collection<ClassAttributeEntity> getClassAttributesById() {
            return classAttributesById;
        public void setClassAttributesById(Collection<ClassAttributeEntity> classAttributesById) {
            this.classAttributesById = classAttributesById;
    @Entity
    @Table( schema = "dbo", name = "class_attribute")
    public class ClassAttributeEntity{
    private Long id;
            @Id
         @Column(name="id")
         @GeneratedValue(strategy= GenerationType.IDENTITY)
        public Long getId() {
              return id;
         public void setId(Long id) {
              this.id = id;
        private ClassEntity classByClassId;
        @ManyToOne
        @JoinColumn(name = "class_id", referencedColumnName = "id")
        public ClassEntity getClassByClassId() {
            return classByClassId;
        public void setClassByClassId(ClassEntity classByClassId) {
            this.classByClassId = classByClassId;
      I want to execute JPQL query
    "SELECT c FROM ClassEntity c"
    ; But I get this exception:
    javax.persistence.PersistenceException: The relationship >>classAttributesById<< of entity {test.ClassEntity(id=1686)}cannot be loaded because the entity is detached
      I can overcome it using EAGER loading -
    @OneToMany(mappedBy = "classByClassId", fetch=FetchType.EAGER)
    , but I really dont need ClassAttributes in this situation! I have many thousands of classes and eager loading provides extremly poor perfomance. What can I do with this problem?
      Thanks in advance for any advice.

    Hi Andrey,
    I assume you are getting the exception if you atempt to access "classAttributesById" ouside the transaction, in which you executed the query, i.e. after the persistence context, in which the query has been executed is closed.
    You have got to make sure that all entities you need to access are read as long as the persistence context executing the query is still open.
    How to address this depends a bit on whether you need to access all related entites or only some.
    If you need to access the relationship "classAttributesById" for only some instances of "ClassEntity", you could for example call size() on "classAttributesById" for these selected instances of "ClassEntity" (within the same transaction/persistence context".
    If you need to access all related entities, theoretically, fetchType = EAGER would be the right choice. However, as you have observed, SAP JPA can't handle this efficiently at the time beeing. Therefore,
    I'd rather suggest that you firstly load all related attributes with a query
    "SELECT ca FROM ClassAttributeEntity ca"
    and secondly load the "ClassEntity"s
    "SELECT c FROM ClassEntity c"
    this should execute efficiently.
    Sorry for the inconvenience.
    -Adrian

  • JPA - Cannot Persist Detached Entity (Java EE 5)

    Hi All,
    I need your advice on identify what appears to be a persisting a detached School (ManyToMany) entity but could not understand why this is occurring:
    1.     The data supplied is made up of detail between counties and surrounding schools. There are a dozen of schools on average in any county. However, there
    will be some over-lapping schools that are a long the border of adjacent counties. For instance, county 1 consists of A, B, C, D, E, F, G, H, I, J, K, L schools while county 2
    (next to each other) is made up of M, N, B, O, P, Q, R, E, S, T, U, H schools. The common ones are B, E and H and are stored as duplicate records in the
    SCHOOL table.
    2.     
    3.     Lets look at the following code snippets on my attempt to come up with a solution without success still for quite sometime:  
    4.      
    5.     @Entity 
    6.     @IdClass(CountyPK.class)  
    7.     @Table(name="COUNTY", catalog="CountyDB", schema="")  
    8.     public class County implements Serializable {  
    9.           
    10.         @Id 
    11.         @Column(name="ZIPCODE")  
    12.         private String zipcode;  
    13.      
    14.         @Id 
    15.         @Column(name="COUNTY")  
    16.         private String county;  
    17.      
    18.         @Id 
    19.         @Enumerated(EnumType.STRING)  
    20.         @Column(name="STATE")  
    21.         @ManyToMany(cascade={CascadeType.PERSIST}, fetch=FetchType.EAGER)  
    22.         @JoinTable(name="COUNTY_SCHOOL", catalog="CountyDB", schema="",  
    23.                    joinColumns={@JoinColumn(name="ZIPCODE", referencedColumnName="ZIPCODE"),  
    24.                                 @JoinColumn(name="COUNTY", referencedColumnName="COUNTY"),  
    25.                                 @JoinColumn(name="STATE", referencedColumnName="STATE")},  
    26.                    inverseJoinColumns={@JoinColumn(name="SCHOOL", referencedColumnName="ID")})  
    27.         private Set<School>; schools = new HashSet<School>();  
    28.         public Set<School> getSchools()  
    29.         {  
    30.         return schools;  
    31.         }  
    32.         public void setSchools(Set<School> hotels)  
    33.         {  
    34.         this.schools = schools;  
    35.         }  
    36.     }  
    37.      
    38.     @Entity 
    39.     @Table(name="SCHOOL", catalog="CountyDB", schema="")  
    40.     public class School implements Serializable {  
    41.      
    42.         @Id 
    43.         @GeneratedValue(strategy = GenerationType.IDENTITY)  
    44.         @Column(name="ID")  
    45.         private int id;  
    46.      
    47.         @Column(name="SCHOOL_NAME")  
    48.         private String schoolName;  
    49.      
    50.         @ManyToMany(mappedBy="schools", cascade={CascadeType.ALL}, fetch=FetchType.EAGER)  
    51.         private Set<County> counties = new HashSet<County>();  
    52.         public Set<County> getCounties()  
    53.         {  
    54.         return counties;  
    55.         }  
    56.         public void setCounties(Set<County> counties)  
    57.         {  
    58.         this.counties = counties;  
    59.         }  
    60.      
    61.     @Stateless 
    62.     public class CountyBean implements CountyRemote {  
    63.           
    64.         @PersistenceContext(unitName="CountyDB-PU") private EntityManager manager;  
    65.           
    66.         public void createCounty(County county)  
    67.         {  
    68.             manager.persist(county);  
    69.             manager.flush();
    70.         }  
    71.      
    72.         public void saveOrUpdateCounty(County county)  
    73.         {  
    74.             manager.merge(county);
    75.             manager.flush();
    76.         }  
    77.      
    78.      
    79.         public County findCounty(String zipcode, String county, State state)  
    80.         {  
    81.             CountyPK pk = new CountyPK(zipcode, county, state);  
    82.             return manager.find(County.class, pk);  
    83.         }  
    84.           
    85.         public List fetchCountiesWithRelationships()  
    86.         {  
    87.           List list = manager.createQuery("SELECT DISTINCT c FROM County c LEFT JOIN FETCH c.counties").getResultList();  
    88.           for (Object obj : list)  
    89.           {  
    90.              County county = (County)obj;  
    91.           }  
    92.           return list;  
    93.        }  
    94.      
    95.     @Stateless 
    96.     public class SchoolBean implements SchoolRemote {  
    97.           
    98.         @PersistenceContext(unitName="CountyDB-PU") private EntityManager manager;  
    99.           
    100.         public void createSchool(School school)  
    101.         {  
    102.             manager.persist(school);  
    103.         }  
    104.      
    105.         public void saveOrUpdateSchool(School school)  
    106.         {  
    107.             manager.merge(school);  
    108.         }  
    109.      
    110.         public School findSchool(int school_id)  
    111.         {  
    112.             return manager.find(School.class, school_id);  
    113.         }  
    114.      
    115.         public School findSchool(String schoolName)  
    116.         {  
    117.             School school = null;
    118.             Query query = manager.createQuery("Select s FROM School s where s.schoolName = :schoolName");
    119.             query.setParameter("schoolName", schoolName);
    120.             List list = query.getResultList();
    121.             for (Object obj : list)
    122.             {
    123.                 school = (School)obj;
    124.                 if (school.getSchoolName().matches(schoolName))
    125.                     return school;
    126.             }
    127.             return school;   
    128.         }  
    129.                 
    130.         public List fetchSchoolsWithRelationships()  
    131.         {  
    132.              List list = manager.createQuery("SELECT DISTINCT s FROM School s LEFT JOIN FETCH s.schools").getResultList();  
    133.              for (Object obj : list)  
    134.              {  
    135.                  School school = (School)obj;  
    136.              }  
    137.              return list;  
    138.         }  
    139.     }  
    140.      
    141.     public class ApplicationClientAddCounty {  
    142.      
    143.         @EJB 
    144.         private static CountyRemote remoteCountybean;  
    145.         @EJB 
    146.         private static SchoolRemote remoteSchoolbean;  
    147.      
    148.         public static void main(String[] args)
    149.         {  
    150.             BufferedReader br = new BufferedReader(new FileReader("COUNTY.XML"));   
    151.             while (countyList_iterator.hasNext())  
    152.             {  
    153.                 County county = new County();  
    154.                 county.setZipcode(((org.jdom.Element)countyList_iterator.next()).getChild("zipcode");  
    155.                 while (schoolList_iterator.hasNext())  
    156.                 {  
    157.                     String school_name = ((org.jdom.Content)schoolsList_iterator.next()).getValue();  
    158.                     if (school_name.length() != 0)  
    159.                     {  
    160.                          School school = null;  
    161.                          if (!school_name.contains("Schools:"))  
    162.                          {  
    163.                               school = remoteSchoolbean.findSchool(school_name);
    164.                               if (school == null)
    165.                               {
    166.                                   school = new School();
    167.                                   school.setSchoolName(school_name);
    168.                               }
    169.                               county.getSchools().add(school);  
    170.                           }  
    171.                      }
    172.                 }  
    173.            }  
    174.            remoteCountybean.createCounty(county);
    175.     } Below is the a simplistic set of the data available which resulted in deplicate School records being persisted:
    COUNTY
    ID     Name
    1     County 1
    2     County 2
    COUNTY_SCHOOL
    ID     COUNTY_ID     SCHOOL_ID
    1     County 2     1
    2     County 1     2
       SCHOOL
    ID     Name
    1     School A
    2     School A
    Yet I wanted only a single normalized School to be generated instead:
    COUNTY
    ID     Name
    1     County 1
    2     County 2
    COUNTY_SCHOOL
    ID     COUNTY_ID     SCHOOL_ID
    1     County 1     1
    2     County 2     1
       SCHOOL
    ID     Name
    1     School A    I am not clear on why the following behavior is taking place within JPA:
    ( i ) The ID for County 1 in COUNTY_SCHOOL is 2 instead of 1. Vice versa for County 2.
    ( ii ) More importantly, why is School A being populated twice even though the data is identical.
    There appears to be some transactional issue/delay using the container managed JTA. Another intriguing symptom is that the following exception occurred after having taken out the @GeneratedValue(strategy = GenerationType.IDENTITY) in School.java in the hope that only a single record is generated:
    *EJB5018: An exception was thrown during an ejb invocation on [CountyBean]*
    javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean; nested exception is: javax.persistence.EntityExistsException:
    *Exception Description: Cannot persist detached object [domain.School@ce9fa6].*
    Class> domain.School Primary Key> [0]
    javax.persistence.EntityExistsException:
    *Exception Description: Cannot persist detached object [domain.School@ce9fa6].*
    Class> domain.School Primary Key> [0]
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:224)
    at com.sun.enterprise.util.EntityManagerWrapper.persist(EntityManagerWrapper.java:440)
    at ejb.CountyBean.createCounty(CountyBean.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    oracle.toplink.essentials.exceptions.ValidationException
    *... 38 more*
    On the other hand, another database exception occurred when directly persisting County & School using remoteCountybean.createCounty(county) as opposed to sending it through a message queue with sendJMSMessageToMyQueue(county) which works:
    *02/02/2011 5:22:14 PM com.sun.enterprise.appclient.MainWithModuleSupport <init>*
    WARNING: ACC003: Application threw an exception.
    javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.RemoteException: null; nested exception is:
    javax.persistence.EntityExistsException:
    *Exception Description: Cannot persist detached object [domain.School@1fcea34].*
    Class> domain.School Primary Key> [1]
    Caused by: javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.RemoteException: null; nested exception is:
    javax.persistence.EntityExistsException:
    *Exception Description: Cannot persist detached object [domain.School@1fcea34].*
    Class> domain.School Primary Key> [1]
    at ejb._CountyRemote_Wrapper.createCounty(ejb/_CountyRemote_Wrapper.java)
    at addCounty(localImportCounty.java:296)I am running JDK1.6.0_17, GF 2.1 on XP. This is a Java EE 5 Enterprise Application.
    It would be much appreciated for some guidance in an unfamiliar territory. I have had many attempts and read up quite a number of similar threats
    But none offer concrete results.
    Thanks in advance,
    Jack

    Hi,
    A minor correction of the last statement in ApplicationClientAddCounty class below:
    141.     public class ApplicationClientAddCounty {  
    142.      
    143.         @EJB 
    144.         private static CountyRemote remoteCountybean;  
    145.         @EJB 
    146.         private static SchoolRemote remoteSchoolbean;  
    147.      
    148.         public static void main(String[] args)
    149.         {  
    150.             BufferedReader br = new BufferedReader(new FileReader("COUNTY.XML"));   
    151.             while (countyList_iterator.hasNext())  
    152.             {  
    153.                 County county = new County();  
    154.                 county.setZipcode(((org.jdom.Element)countyList_iterator.next()).getChild("zipcode");  
    155.                 while (schoolList_iterator.hasNext())  
    156.                 {  
    157.                     String school_name = ((org.jdom.Content)schoolsList_iterator.next()).getValue();  
    158.                     if (school_name.length() != 0)  
    159.                     {  
    160.                          School school = null;  
    161.                          if (!school_name.contains("Schools:"))  
    162.                          {  
    163.                               school = remoteSchoolbean.findSchool(school_name);
    164.                               if (school == null)
    165.                               {
    166.                                   school = new School();
    167.                                   school.setSchoolName(school_name);
    168.                               }
    169.                               county.getSchools().add(school);  
    170.                           }  
    171.                      }
    172.                 }
    173.                remoteCountybean.createCounty(county);
    173.            }  
    174.     } Thanks,
    Jack

  • JPA Bug !?

    Hi,
    I'm building a web shop using JPA.
    A couple of my entities are Category(as in category of items) and Item. Here is a minimized code preview :
    @Entity
    @Table(name = "category")
    @NamedQueries(....)
    public class Category implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = true, fetch = FetchType.EAGER)
    @Column(name = "categoryId")
    private Integer categoryId;
    @OneToMany(mappedBy = "categoryId", cascade = CascadeType.REMOVE)
    private List<Item> itemCollection;
    @Entity
    @Table(name = "item")
    @NamedQueries(....)
    public class Item implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = true, fetch = FetchType.EAGER)
    @Column(name = "itemId")
    private Integer itemId;
    @JoinColumn(name = "categoryId", referencedColumnName = "categoryId", updatable=true)
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private Category categoryId;
    Now my problem is that, after creating a new Item, this method doesn't return it :
    public List<Item> getItemsByCategory(int categoryId) {
    Category category = (Category)entityManager.createNamedQuery("Category.findByCategoryId").setParameter("categoryId", categoryId).getSingleResult();
    List<Item> itemsOfThisCat = category.getItemCollection();
    return itemsOfThisCat;
    Just to make it clear, there is no error, the newly created Item is in db, but it is returned by the above method only if restart the server or redeploy the application !!!!?
    I have this problem both for TopLink and OpenJPA, and I am completing the entire project by my self, from the web design to the db optimization, so I could really use a good and concise advice.
    Cheers,
    Cristi

    I found it natural that JPA will add by itself a newly created Item to the List<Item> of the Category entity.
    I hate it when I get stuck in such small issues, thank u so much for your reply.

  • JPA persist() or merge()

    Hi All,
    I would like to get clarification between using JPA persist() and merge() where there is a OneToMany EMPLOYEE table unidirectionally joint to ManyToOne TELEPHONE table.
    The code snippet for OneToMany Employee.java entity object is as follows:
    @Entity
    @IdClass(EmployeePK.class)
    @Table(name="EMPLOYEE", catalog="CorporationDB", schema="")
    public class Employee implements Serializable {  
    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
        @JoinTable(name="EMPLOYEE_TELEPHONE", catalog="CorporationDB", schema="",
                   joinColumns={@JoinColumn(name="FIRSTNAME", referencedColumnName="FIRSTNAME"),
                                @JoinColumn(name="SURNAME", referencedColumnName="SURNAME"),
                                @JoinColumn(name="AGE", referencedColumnName="AGE"),
                                @JoinColumn(name="SEX", referencedColumnName="SEX")},
                   inverseJoinColumns={@JoinColumn(name="TELEPHONE_ID")})
            private Collection<Telephone> telephones = new ArrayList<Telephone>();
        public Collection<Telephone> getTelephones()
         return telephones;
        public void setTelephones(Collection<Telephone> telephones)
         this.telephones = telephones;
        }The corresponding detail for ManyToOne Telephone.java entity object is:
    @Entity
    @Table(name="TELEPHONE", catalog="CorporationDB", schema="")
    public class Telephone implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name="ID")
        private int id;
        @Column(name="TELEPHONE")
        private String telephone;
        public void setTelephone(String telephone) {
            this.telephone = telephone;
        public String getTelephone() {
            return telephone;
        }I would like JPA to to ignore (not overwrite) existing record and only add newer unique telephone numbers. persist() does that except it is throwing the following exceptions and continually re-trying to insert the duplicate records:
    Local Exception Stack:
    *Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))): oracle.toplink.essentials.exceptions.DatabaseException*
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry Allan-Smith-20-M' for key 'PRIMARY'
    Error Code: 1062
    Call: INSERT INTO CorporationDB.EMPLOYEE (FIRSTNAME, SURNAME, AGE, SEX.....) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    *bind => [Allan, Smith, 20, M,....]*
    Query: InsertObjectQuery(finance.Employee@1d2d80c)
    JTS5054: Unexpected error occurred in after completion
    On the other hand, merge() ignores (does not add) duplicate Employee record (good) but it still duplicates the ManyToOne TELEPHONE table. Is it because of the OneToMany(cascade={CascadeType.ALL}} property in Employee.java which duplicates TELEPHONE records automatically? As a result, how to ensure that only unique OneToMany (EMPLOYEE) & ManyToOne (TELEPHONE) records are added once?
    persist() seems to work fine except that it is continually erroring out instead of skipping to the next new record.
    This Java EE 5 application is running properly.
    I am running JDK1.6.0_7, GF2.1 and MySQL on Windows XP.
    Thanks in advance,
    Jack

    I would recommend you continue to use TopLink Essentials as your JPA provider by setting your provider in your persistence.xml, or upgrading to EclipseLink and setting it as your provider. The latest WLS release also includes EclipseLink.
    James : http://www.eclipselink.org

  • EJB/JPA Session/Entity Bean: Back Reference Id not set

    Hello All,
    I m using JPA as a persist tool. I have an entity Account and in Account there is a collection of entity AccountDetail. In Account entity relation for AccountDetail is One-To-Many and in AccountDetail the relation for Account is Many-To-One. When i save the Account, object of Account and AccountDetail are saved correctly. But the problem is that in AccountDetail the Id of Account is not saved in Database table. I have AccountId in AccountDetail table. plz help me??
    Second thing is that how to generate automatically primary keys when entity saved in database ???

    define the column you want to auto increment as an Integer with Identity attribute set to True (using the sql server management tool for example) and then put
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    in front of the ID declaration in the mapping file, it should generate the IDs automatically.

  • SAP JPA simple query

    Hello, experts!
      I have a simple entity
    @Entity
    @Table( schema = "dbo", name = "class")
    public class ClassEntity {
      private Long id;
            @Id
         @Column(name="id")
         @GeneratedValue(strategy= GenerationType.IDENTITY)
        public Long getId() {
              return id;
         public void setId(Long id) {
              this.id = id;
    I have about 10.000 records in this table. The simplest query "SELECT c FROM ClassEntity c WHERE c.id=:id" tooks 3-4 seconds! I have found (using mssql profiler) that SAP JPA implementation selects ALL records and only then returns the one I need!
    Moreover, query "SELECT count(c) FROM ClassEntity c" tooks 3-4 seconds too, and its behaviour is the same! Have anyone an idea, whats going on? How can I select just 1 record (ClassEntity) from the table?
      Thanks for any advice.

    Hi Andrey,
    the behavior you are describing would be absolutely unexpected.
    Could you please double check using the SQL Trace (http://<host>:<port>/OpenSQLMonitors) that the generated SQL is a you are describing it.
    -Adrian

  • JPA - Mysql - GeneratedValue

    I am using Mysql with Eclipselink 2.0.1 and have the following situation:
    My Entity is using a field declared like this:
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long referenceNumber;
    The DDL is generated and in my database all tables are created. If I insert a new record within my EJB I am getting as the "referenceNumber" not "1" - I am getting sometimes "50" sometimes "1232". It is a completely random id. Is it possible to get an ID which is starting by 1 and incrementing automatically ?
    I have tried to use GenerationType.IDENTY but this has some problems with cascading operations, so I do not want to use it.

    Hello,
    I just started playing with JPA and mysql. My tables's primary keys use auto-increment option in database. To tell application how to work with these fields I use following statements and everything works perfect after some troubles in the beggining of course :-)) :
    @Entity
    @Table(name = "C_ADRESA_TYP") //, schema = "KMPV"
    public class CiselnikAdresaTyp implements Serializable{
         private static final long serialVersionUID = 1L;
         @Id
         //@Required - cannot be used when using auto-increment and IDENTITY gerenator
         @Hidden
         @Column(name = "PK_ADRESA_TYP", insertable = false, nullable = false, updatable = true)
         @GeneratedValue(strategy=GenerationType.IDENTITY)
         private int pkAdresaTyp;
         @Required
         @Column(name = "KOD", length = 30, nullable = false, updatable = true)
         private String kod;
    .....etc
    In case of you are experiencing still some troubles witch some cascade actions, this could be regarding your foreing keys, exactly on on update on delete actions.
    Hope it'll help.
    archenroot
    Edited by: user8916162 on Nov 9, 2010 11:18 AM

  • Automatically Add JPA Annotations

    Hi,
    I am not sure if my question is annotation specific, maybe it is more generally about generating source code.... here is what I want to do:
    I want to use JPA annotations to declare the O/R mapping of my domain classes, but actually I don't want to write these annotations manually. I want to generate them automatically based on name patterns.
    e.g. I have the following class:
    public class Permission  {
        private Integer permissionID;
        private Set <AccountGroup> accountGroups = new HashSet<AccountGroup>();
    }... now I want to write a java program that adds annotations based on name patterns and get something like:
        @Id
        @Column( name = "permissionID", updatable = false, nullable = false )
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer permissionID;
        @ManyToMany (
            targetEntity = AccountGroup.class
        @JoinTable (
            name = "Permission_AccountGroup",
            joinColumns = @JoinColumn (name="permissionID"),
            inverseJoinColumns = @JoinColumn (name="accountGroupID")
        private Set <AccountGroup> accountGroups = new HashSet<AccountGroup>();What is the easiest way to insert the annotations into the source code? ... I am thinking about methods like "addAnnotationToClass / Field" ... any idea?

    Hi there...
    I just made a similar question.
    i have tested and i have the same problem.
    the solution i found at the moment for me was to move back to 10.2.1. As this are minor versions, i just uninstalled 10.2.2, got a copy of itunes 10.2.1 from oldapps website and installed that one, and seems are back to normal.
    Fred

  • JPA: How to initialise an entity for a self-referencing table?

    I am working on a project that requires a self-referencing table:
    mysql> show create table attributes\G
    *************************** 1. row ***************************
           Table: attributes
    Create Table: CREATE TABLE `attributes` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `parent` int(11) DEFAULT NULL,
      `type` int(11) DEFAULT NULL,
      `name` varchar(128) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `parent` (`parent`),
      KEY `type` (`type`),
      CONSTRAINT `attributes_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
      CONSTRAINT `attributes_ibfk_2` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
    I used NetBeans to generate an entity class from the table:
    @Entity
    @Table(name = "attributes")
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
        @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
        @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name")})
    public class Attributes implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "id")
        private Integer id;
        @Size(max = 128)
        @Column(name = "name")
        private String name;
        @OneToMany(mappedBy = "parent")
        private Collection<Attributes> attributesCollection;
        @JoinColumn(name = "parent", referencedColumnName = "id")
        @ManyToOne
        private Attributes parent;
        @OneToMany(mappedBy = "type")
        private Collection<Attributes> attributesCollection1;
        @JoinColumn(name = "type", referencedColumnName = "id")
        @ManyToOne
        private Attributes type;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "attributes")
        private Collection<ItemAttributes> itemAttributesCollection;
        @OneToMany(mappedBy = "ivalue")
        private Collection<ItemAttributes> itemAttributesCollection1;
    But how can I write a constructor for this entity? The auto-generated code gets around the issue by doing nothing; the constructor is empty. I can't help thinking that if I set the parent and type references to anything with new Attributes(), then it will recurse out of control. What else can/shall I do? I know how to rewrite it to not use the entity relations, but I'd prefer to make it work.

    Cymae wrote:
    I don't want to call the hash table creation method because from what i understand about interfaces the idea is that your main method doesnt know the table is actually a hash table...is that right?That's not exactly the idea. The idea to use the interface as the type instead of the implementation, is that your class probably doesn't need to know the full type. This makes it easy to change the implementation of the interface if needed. However, somebody at some point has to create the concrete object, a HashTable.
    Basically, an interface describes a behavior, and a class that implements an interface decides how to actually perform this behavior. It is obviously impossible to perform the behavior if you are not told how to perform it.
    Table table = new HashTable() is the correct way to do it. This means that if you ever need you Table implementation to change, the only thing you need to change in your whole class is this line. For example you might want Table table = new FileTable().

  • JPA One to One Mapping problem

    [Please see Image|http://caterpillar.onlyfun.net/Gossip/EJB3Gossip/images/OneToOneSharedPK-1.jpg]
    The primary key (@PrimaryKeyJoinColumn ) cannot join to 'Room Table'.
    what mistake?
    @Entity
    @Table(name="T_USER")
    public class User implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
       @Column(name = "USER_ID")
        private Integer userId;
        @Column(name = "NAME")
        private String name;
        @Column(name = "AGE")
        private String age;
        @OneToOne(cascade=CascadeType.ALL)
        @PrimaryKeyJoinColumn(name="USER_ID" , referencedColumnName="ROOM_ID")
        private Room room;
       // getter and setter missing
    @Entity
    @Table(name="T_ROOM")
    public class Room implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ROOM_ID")
        private Integer roomId;
        @Column(name = "ADDRESS")
        private String address;
    // getter and setter missing
    }Edited by: lauangus on 2010?4?21? ??3:24

    There are several things missing here.
    For serializable, you should always have a unique:
    private static final long serialVersionUID =1234L;
    Here is an example that actually works, adapted to your classes:
    @OneToOne( cascade = CascadeType.REFRESH, optional = false )
    @JoinTable( name = "USER_ROOM", joinColumns = @JoinColumn( name = "USER_ID" ),
    inverseJoinColumns = @JoinColumn( name = "ROOM_ID" ) )
    You may also want to investigate the following annotations depending on your DB:
    @GeneratedValue
    @SequenceGenerator
    You may want to generate your case using beanwizard.com to see how a working version is configured.

  • OneToMany + EmbeddedId + GeneratedValue(IDENTITY)

    Hello everybody.. I need your help..
    I have the tables:
    CREATE TABLE CLIENTE (
         ID     INTEGER          NOT NULL AUTO_INCREMENT,
         NOME     VARCHAR(50)     NULL,
         PRIMARY KEY(ID));
    CREATE TABLE TELEFONE (
         ID_CLIENTE     INTEGER     NOT NULL,
         TELEFONE     VARCHAR(20)     NOT NULL,
         PRIMARY KEY(ID_CLIENTE, TELEFONE),
         FOREIGN KEY (ID_CLIENTE) REFERENCES CLIENTE(ID));
    And the mappings:
    (1)
    @Entity
    public class Cliente implements Serializable {
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Long id;
        private String nome;
        @OneToMany(cascade=CascadeType.ALL, mappedBy="cliente")
        private Collection<Telefone> colTelefones;
        // getters and setters
    public class Telefone implements Serializable {
        @EmbeddedId
        private TelefoneId telefoneId;
        @ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name="ID_CLIENTE")
        private Cliente cliente;
        // getters and setters without mappings.
    @Embeddable
    public class TelefoneId implements Serializable {
        @Column(name="ID_CLIENTE", insertable=false, updatable=false)
        private Long idCliente;
        private String telefone;
        // getters and setters
    }This works in Toplink, but doesn't works in Hibernate. I tried also this mapping below. It works in Hibernate EntityManager but doesn't work in Toplink.
    (2)
    @Entity
    public class Cliente implements Serializable {
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Long id;
        private String nome;
        @OneToMany(cascade=CascadeType.ALL, mappedBy="telefoneId.cliente")
        private Collection<Telefone> colTelefones;
        // getters and setters
    public class Telefone implements Serializable {
        @EmbeddedId
        private TelefoneId telefoneId;
        // getters and setters
    @Embeddable
    public class TelefoneId implements Serializable {
        @ManyToOne
        @JoinColumn(name="ID_CLIENTE", cascade=CascadeType.ALL)
        private Cliente cliente;
        private String telefone;
        // getters and setters
    }Can you help me to find a solution that work in both implementations???
    PS: I want to persist "Cliente" and after persist "Telefone" by cascade. I want that framework put the Generated Id for Cliente in Telefone object.
    Thanks for your attention.
    Regards,
    Nando.
    Edited by: user10343079 on 10/12/2009 19:09

    wlin wrote:
    If I change "private Long statsId" to "private Long stats_id", also change get and set methods, it works. But it is not the right way to do it.I'd agree with you there, this smells like a bug in EclipseLink (or at least the version provided by Glassfish). If you want to make the effort, I'd check here if a bug report that matches your description already exists, and if not file a new one:
    https://bugs.eclipse.org/bugs/

Maybe you are looking for

  • How to manually edit a "Table of Contents"

    How do I set a table of contents to display "..." or align in a "nicer way" - either through manual editing or some advanced automatic vodoo. Right now my TOC looks like this: Uploaded with plasq's Skitch! And that's not a good thing.

  • How to use the third party apps?

    I see Apple has put some third party apps on their site, but how do you download them and use them for itouch?

  • Upgrade of cucm

    Hi everybody, I would like to upgrade my current cucm 7.1.5 to be6k 9.1.2 on new servers. First of all is it a recommended upgrade path using jump upgrade? On is it much safer to start a new clean installation? If i choose the jump upgrade i would li

  • 9320 not syncing with Outlook 2003

    Hi, I've given up trying to get a calendar app that will display calendar and tasks logically like Touch Pro used to when it was possible to register it. Now the problem is my 9320 has stopped syncing with Outlook 2003, first it was tasks, then notes

  • Consolidation of MAC and Bootcamp HD's

    Please instruct me on how to consolidate the Bootcamp Petition. I want my harddrive space back on the Macintosh HD.