Search code examples
javaoopjpaforeign-keysauto-generate

setting an id autogenerate into an object


Sorry if my post is duplicated or the tittle doesn't describe the topics, because I don't know how to describe this in the tittle, I look on internet, but I didn't find the solution.

I am using Java and JPA. The problem is the next :

I have a class A with an autogenerated key :

class A{
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private int id;
      private List<B> listB;
}

And the class B with the id of this clas:

 class B {
         @EmbeddedId
         private Bid id;
         private String att;
     }
     class Bid {
         private int idA;
         private String text;
     }

In a controller I want to create an object A, the problem is when I created the object A, I need to create the object B where the id of B contains the id of A which is autogenerated, and it is created in the moment when the entity is mapped to de database, I dont't know how to set the id autogenerated of A into the idB, maybe I should query to de database asking what is the las id of classA, but it seem bad.

Thanks in advance


Solution

  • Your case is a derived identifier case, where your entity B's identity was derived from the primary key of A. You can use @MapsId annotation for this case and your entities can be restructured like this:

    @Entity
    public class A {
    
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private int id;
    
      @OneToMany(mappedBy="a")
      private List<B> listB = new ArrayList<B>();
      ...
    }
    
    @Entity
    public class B {
        @EmbeddedId
        private BId id;
    
        @ManyToOne
        @MapsId("idA")
        private A a;
        ...
    }
    
    @Embeddable
    public class BId {
        private int idA;
        private String att;
        ...
    }
    

    This is how you would persist the entities:

    A a = new A();
    
    BId bid = new BId();
    bid.setAtt("text"); // notice that the idA attribute is never manually set, since it is derived from A
    
    B b = new B();
    b.setId(bid);
    b.setA(a);
    
    a.getListB().add(b);
    
    em.persist(a);
    em.persist(b);
    

    See sample implementation here.