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

    Generate ID when creating entities

    Thomas Hamacher Novice


      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.


        • 1. Re: Generate ID when creating entities
          Tim Cupp Newbie

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

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



          • 2. Re: Generate ID when creating entities
            Thomas Hamacher Novice


            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