Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: insert data with foreign key

Tags:

java

hibernate

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?

like image 604
user2035039 Avatar asked Mar 16 '16 12:03

user2035039


2 Answers

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)
like image 128
Cootri Avatar answered Nov 16 '22 06:11

Cootri


Just put a new User into your Calendar:

Calendar c = new Calendar();
c.setOwner(new User(id));
like image 31
Jordi Castilla Avatar answered Nov 16 '22 06:11

Jordi Castilla