Hibernate version:
Hibernate 3.2.6
Hibernate-Annotations 3.3.1
Hibernate-EntityManager 3.3.2
Name and version of the database you are using:
SQL Server 2005
The problem/question:
I'm having problems understanding the id generation with Hibernate.
First I'll tell you guys what I have right now. I have a TextMessage business object (will show you the code later on) and I want to store it in the database. At the moment the id (PK) is generated at table-level. So I don't have an id until the TextMessage instance has been stored.
At the moment my create method in de TextMessageDAO looks like this:
Code:
public void create(TextMessage textMessage, EntityManager em) {
/*
* Before the TextMessage instance is stored the changedDate
* will be set.
*/
textMessage.setChangedDate(new Date());
em.persist(textMessage);
}
The em.persist returns a void, so I wonder: how can I get the value of id that has been generated. Should I retrieve the latest textMessage based on the changedDate (this would require a lock around the entire method to make sure no other textMessage is stored in the meantime), or is there another way to retrieve the id?
What I would like better is that Hibernate generates an id for me. I've tried to do this, but I always get an error during storage, because Hibernate tries to insert NULL into my PK field. If it is possible to have Hibernate generate an id for me (and thus removing the need to retrieve the id from the database afster storage) that would have my preference.
The TextMessage business objectCode:
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.persistence.*;
@Entity
@Table(name="TEXT_MESSAGE")
public class TextMessage {
private Long id;
private String message;
private Date sendDate;
private String apiMessageId;
private Date changedDate;
public TextMessage() {}
@Id @GeneratedValue(strategy=GenerationType.TABLE)
@Column(name = "MESSAGE_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="MESSAGE")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Column(name="SEND_DATE")
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
@Column(name="API_MESSAGE_ID")
public String getApiMessageId() {
return apiMessageId;
}
public void setApiMessageId(String apiMessageId) {
this.apiMessageId = apiMessageId;
}
@Column(name="CHANGED_DATE")
public Date getChangedDate() {
return changedDate;
}
public void setChangedDate(Date changedDate) {
this.changedDate = changedDate;
}
Kind regards,
Rick Veenstra