This error is always reported when you insert an image using Hibernate today:
Data truncation: Data too long for column 'photo' at row 1
Let's talk about the cause of the error first.
This photo is defined in this way: private byte [] photo; because I configured it in hibernate. cfg. xml
<Property name = "hibernate. hbm2ddl. auto"> update </property>: The table structure is automatically generated.
An error occurs when the photo column in the table structure is incorrect.
See:
The blob type is generated.
The MySQL document explains this as follows:
BLOB [(M)]
BLOB column with a maximum length of 65,535 (216-1) bytes.
The optional length of this type is M. If given, MySQL creates the column as the BLOB type that is the smallest but sufficient to accommodate the M-byte length value.
The size of the inserted image is greater than this range, so the image cannot be inserted.
Solution:
Change blob to longblob. MySQL of longblob type is explained as follows:
LONGBLOB
A blob column with a maximum length of 4,294,967,295 or 4 GB (232-1) bytes. The maximum valid (allowed) Length of the LONGBLOB column depends on the maximum package size and available memory configured in the Client/Server protocol.
Sure enough, just change to longblob.
Experience: Sometimes the structure of tables automatically generated by Hibenrate may be different from the actual needs. Therefore, you must check the structure of the automatically generated table through Hibernate. It must meet your actual needs.
In short: Everything starts from reality!
Appendix: Test code
Java code
@ Test
Public void testSave () throws Exception {
InputStream in = new FileInputStream ("src/cat.jpg ");
Byte [] photo = new byte [in. available ()];
System. out. println (in. available (); // 81108
In. read (photo );
In. close ();
User user = new User ();
User. setBirthday (new Date ());
User. setDesc ("description ....");
User. setGender (User. GENDER_FEMALE );
User. setName ("Monday ");
User. setPhoto (photo );
User. setResume ("self-introduction ...");
Session session = sessionFactory. openSession ();
Transaction tx = session. beginTransaction ();
Session. save (user );
Tx. commit ();
Session. close ();
}
Author: "Free party"