Egor Osaulenko Egor Osaulenko - 3 years ago 87
Java Question

How to add property class by it's id with Hibernate?

Have stucked a bit and think - need help.

Suppose I have a class Message, which is a child for a Forum. They have One-to-Many relation in annotation. Something like this:

@Table(name="message", catalog="catalog")
public class Message implements Serializable {
@GeneratedValue(strategy = IDENTITY)
@Column(name="IDMessage", unique = true)
private int idMessage;

@Column(name="Title", columnDefinition="TEXT")
private String title;

@Column(name="Message", columnDefinition="TEXT")
private String message;

private Forum forum;


I don't want to retrieve the Forum object by it's id, attach it to the message and only then save the message.
So I have started to create a wrapper, which will be like:

public class MessageDto {

private int idMessage;
private String title;
private String message;
private int idForum;

And use it whenever I am saving/updating. But I have a very strong feeling that I am doing it wrong.

Simple guiding, in which direction to look for the answer, will be a great help.

Thank you in advance!

Answer Source

In hibernate, you don't need to fetch the object if it already exists. Just create a new Forum with the id (you should have it already). Example:

Message message = new Message();
Forum forum = new Forum();

Hibernate should save it OK.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download