2 Replies Latest reply on Jan 30, 2008 4:40 AM by hamtho2

    Generate ID when creating entities

      Hi,

      is there a chance to let the EntityManager create the ID at creation-time of an entity?

      I´ve got the problem, that I want to share one id between multiple entities while having a unidirectional one-to-one relation.
      This way I only have a generated value at the parent-object and for the dependent entities I have to set the id manually (to the same id, as the parent). Unfortunately the id is only generated when persisting the entity (before that the value is null), so it´s hard to propagate an object-reference to the dependant entities (even with @PrePersist as I would have to parse the parent-object).
      So what I could do is to manually get the next value from my sequence and set this as an id for every entity. But if the id would be generated when a new entity is created, there won´t be a problem at all. Is there a way to achive this?

      Any input would be greatly appriciated.

      Thomas

        • 1. Re: Generate ID when creating entities
          tcupp1

          Use Hibernate annotations and generated values. This is a very quick example, and may not work out of the box.


          public class Parent {
          
          @Id
          @GeneratedValue(strategy = GenerationType.SEQUENCE)
          private Long id
          
          @OneToOne
          @PrimaryKeyJoinColumn
          private Child child;
          }
          
          public class Child {
          
          @Id
          @GeneratedValue(generator="foreignKeyGenerator")
          @org.hibernate.annotations.GenericGenerator(name="foreignKeyGenerator", strategy="foreign",parameters=@Parameter(name="property", value="parent"))
          
          @OneToOne(optional=false)
          @JoinColumn(name="id")
          private Parent parent;
          }
          


          HTH

          Tim

          • 2. Re: Generate ID when creating entities

            Tim,

            thanks a lot for your answer!
            It seems as if this solution only works in a bi-directional one-to-one relation? Is that true? In my case, I don´t have the "Parent"-object in my "Child" as a back-reference. So is it a "must-requirement" to have a bi-directional relation or is there also a way for a uni-directional relation?

            Thanks for help

            Thomas