Posts Tagged 'Annotation'

Hibernate Annotation: length-limited field is not auto truncated

Problem:

Let’s consider a table containing a length-limited field (e.g. COUNTRY_CODE is 2-char length).

CREATE TABLE  `country` (

	`COUNTRY_CODE` varchar(2),
	`COUNTRY_NAME` varchar(255),

) 

- The length value is already specified in Hibernate annotation.

@Column(name="COUNTRY_CODE", length=2)
private String countryCode;

- However when inserting a value length beyond the limit, this value is not automatically truncated, and Hibernate throws the following exception:

Caused by: java.sql.BatchUpdateException: Data truncation: Data too long for column 'COUNTRY_CODE' at row 1

Solution: Use custom SQL :

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.SQLInsert;

/**
* The persistent class for the country database table.
*
*/
@Entity
@Table(name="country")
@SQLInsert(sql="INSERT IGNORE INTO country (country_name, country_code) VALUES(?,upper(?))")
public class Country {

	@Id
	@Column(name="COUNTRY_CODE", length=2)
	private String countryCode;

	@Column(name="COUNTRY_NAME")
	private String countryName;

	//bi-directional many-to-one association to State
	@OneToMany(mappedBy="country")
	private List<State> states;

	//... standard getters and setters

}
25 January 2010 at 21:04 - Comments