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.

About these ads

About ChandanPandey

Try to come up with a good design as by product of good coding practices

Posted on January 4, 2013, in Hibernate, Java and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 32 other followers

%d bloggers like this: