Blog Archives
Data truncation exception while joining one to one in JPA
Lets say a class is having one to one relation ship with other entity, it looks like
public class StudentDetails implements Serializable{ @OneToOne(cascade={CascadeType.REFRESH,CascadeType.MERGE},fetch = FetchType.EAGER) @Column(name="classid") private ClassDetails classId; }
When I tried to save rows in the table, it threw an exception
javax.persistence.PersistenceException: org.hibernate.exception.DataException: Data truncation: Data too long for column 'classid' at row 1 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1306) }
What went wrong? When I looked at generated table the filed type for classid was LOB while I expected it to be an int (It just an ID from foreign key). The culprit is -using column instead of joincolumn
public class StudentDetails implements Serializable{ @OneToOne(cascade={CascadeType.REFRESH,CascadeType.MERGE},fetch = FetchType.EAGER) @Column(name="classid") private ClassDetails classId; Instead of column, it should be join column @OneToOne(cascade={CascadeType.REFRESH,CascadeType.MERGE},fetch = FetchType.EAGER) @JoinColumn(name="classid",nullable=false) <strong> See the joincolumn </strong> private ClassDetails classId;}
If join column is not specified, JPA assumes that ClassDetails object will be saved (along with its all nested graph) to DB and hence it creates a LOB type -telling it that its a joined foreign key resulted in a int data type for the field.