0

I have 2 entities that use the same sequence as the primary key, how do I map? Example:

@Entity
@Table("employeT")
    public class Employe(){
          @SequenceGenerator(name = "generator_id", sequenceName = "seq_id") 
          @GeneratedValue(generator = "generator_id")
          @colunm(name = "id")
          private Integer id;

          @colunm(name = "nameEmp")
          private String name;

          @JoinColumn(name = "id")
          private Computer computer;
}

@Entity
@Table("computerT")
    public class Computer(){
          @SequenceGenerator(name = "generator_id", sequenceName = "seq_id") 
          @GeneratedValue(generator = "generator_id")
          @colunm(name = "id")
          private Integer id;

          @colunm(name="name_computer")
          private String nameComputer;
}

I need save employe and computer with same id, generated by Employe save.

  • https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#identifiers-derived – JB Nizet Oct 15 '18 at 19:42

1 Answers1

2

There are three things to do with your code to work the way to want to.

  1. Add @OneToOne annotation to indicate that Employee and Computer are in relation.
  2. Delete information about @SequenceGenerator from your Computer entity and add @Id annotation
  3. Add @MapsId annotation. [More info]

So it would look something like this :

@Entity
@Table("employeT")
public class Employe(){
          @Id
          private Integer id;

          @Colunm(name = "nameEmp")
          private String name;


          @OneToOne
          @JoinColumn(name = "computer_id")
          @MapsId
          private Computer computer;
}

Why?

@OneToOne annotation indicates relation between entities.

@SequenceGenerator is redudant since we "copy" id from Computer entity.

@Id annotation is mandatory to indicate that this field is our primary key.

Last but not least, @MapsId annotation do the magic, where it 'borrows' id from relation.

More info in the link I attached earlier.

Emil Hotkowski
  • 2,233
  • 1
  • 13
  • 19
  • Isnt working, that's the error: "attempted to assign id from null one-to-one property " – olivier duque Oct 15 '18 at 20:13
  • You are trying to save Employee where Employee.computer is null, put there your computer entitiy (which is saved) or put computer object and CascadeType : ) – Emil Hotkowski Oct 15 '18 at 20:34
  • @olivierduque here is same error https://stackoverflow.com/questions/11104897/hibernate-attempted-to-assign-id-from-null-one-to-one-property-employee – Emil Hotkowski Oct 15 '18 at 20:34