I have the following two tables in my database:
Calendar(id, name, user_id)
User(id, name, ...)
Each calendar is owned by one user, each user can have multiple calendars. Hence, there is a many-to-one relationship from Calendar to User. Now I'd like to insert a set of data into my Calendar table, my Calendar Entity looks like this:
@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 am inserting the data set, I do know the owner's id, but I don't have the corresponding User
object. Do I have to retrieve the User
object, set owner
to it and then insert the data set?
This sounds a little inconvenient to me, is there a way to insert the data set using the User
id as it would be stored in the database, as opposed to using a User
object?
you can get User proxy instance with the given owner's id (it is cheap operation). Then use this instance as 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)
Just put a new User
into your Calendar
:
Calendar c = new Calendar();
c.setOwner(new User(id));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With