Sleep mode: insert data using a foreign key

My database has the following two tables:

Calendar (id, name, user_id)

User (id, name, ...)

Each calendar belongs to one user, each user can have several calendars. Therefore, there is a many-to-one relationship from the Calendar to the User. Now I would like to insert a dataset into my calendar table, my calendar object is as follows:

@Entity @Table(name = "calendar") public class Calendar { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(name = "id", columnDefinition = "BINARY(16)") private UUID id; @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "owner", referencedColumnName = "id") private User owner; ... } 

However, when I insert the data set, I know the owner ID, but I do not have the corresponding User object. Should I get a User object, set owner for it, and then insert a dataset?

This sounds a little inconvenient for me, is there a way to insert a dataset using the User identifier, since it will be stored in the database, as opposed to using the User object?

+5
source share
2 answers

you can get an instance of User proxy with this owner ID (this is a cheap operation). Then use this instance as the owner value:

 User dummy = hibernateTemplate.load(User.class, ID); //entityManager.getReference or session.load should do the trick too calendar.setOwner(dummy); hibernateTemplate.save(calendar) 
+1
source

Just put the new User in your Calendar :

 Calendar c = new Calendar(); c.setOwner(new User(id)); 
0
source

Source: https://habr.com/ru/post/1245162/


All Articles