Hi all,
I recently started with hibernate. I have created a business object called textMessage and I want to store it. For the database I have SQL Server 2005, in the database I created a new table called TEXT_MESSAGE and I created a couple of columns. MESSAGE_ID (Primairy key), MESSAGE, SEND_DATE, SENDER_ID and API_MESSAGE_ID.
My business object looks as follows:
Code:
import java.util.Date;
import javax.persistence.*;
@Entity
@Table(name="TEXT_MESSAGE")
public class TextMessage {
private Long id;
private String message;
private String senderId;
private Date sendDate;
private String apiMessageId;
public TextMessage() {}
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@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="SENDER_ID")
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
@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;
}
}
Now I have a DAO class with a method to store the textMessage:
Code:
public class TextMessageDAO {
public void storeTextMessage(TextMessage textMessage) {
//Start EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ricohUnit");
//First unit of work
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(textMessage);
tx.commit();
em.close();
emf.close();
}
}
Now when I execute this method I get an error telling me that the value NULL cannot be inserted into column MESSAGE_ID.
Ofcourse that is correct, it is set as the primairy key.
Code:
Hibernate:
insert
into
TEXT_MESSAGE
(API_MESSAGE_ID, MESSAGE, SEND_DATE, SENDER_ID)
values
(?, ?, ?, ?)
13:00:21,269 WARN JDBCExceptionReporter:77 - SQL Error: 515, SQLState: 23000
13:00:21,269 ERROR JDBCExceptionReporter:78 - Cannot insert the value NULL into column 'MESSAGE_ID', table 'Ricoh-PoC.dbo.TEXT_MESSAGE'; column does not allow nulls. INSERT fails.
Why is Hibernate not inserting MESSAGE_ID with a generated value?
Cheers,
Rick