標籤:
在學習Hibernate中,相信很多人都遇到過:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute statement
Caused by: java.sql.SQLException: Field ‘address_id‘ doesn‘t have a default value
很是納悶,明明我的address_id是主鍵,為毛還提示我不存在預設值?主鍵不是應該自動產生值的嗎?
解決是一方面,知道為什麼報錯才是最重要的。
錯誤原因:
以下拿我這個錯誤來講(address_id)
import java.util.HashSet;import java.util.Set;import javax.persistence.*;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Table;@Entity@Table(name="personSet_inf")public class PersonSet {@Id@Column(name="person_id")/*@GeneratedValue(strategy=GenerationType.IDENTITY)*/private Integer id;private String name;private String age;
在開始我雖然指定了主鍵和主鍵名,但是沒有將address_id作為主鍵設定為@GeneratedValue(strategy=GenerationType.IDENTITY)自增類型(上面代碼以註解),這時運行程式控制台就會報錯:
Exception in thread "main" org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.mao.PersonSet
雖然報這個錯誤,但是hibernate已經建立了一張表(personSet_inf),注意這時表的主鍵不是自增長模式,
而且你想要插入的資料並沒有插入,這時你發現了錯誤,然後在程式中給主鍵添加了自增長類型,重新運行項目,就會報錯:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute statementCaused by: java.sql.SQLException: Field 'address_id' doesn't have a default value
原因就是:你雖然在代碼裡修改了主鍵類型,但是你資料庫表已經建好了,它裡面的主鍵依然不是自增長類型,所id不會自動賦值,然後報錯:id沒有預設值。
解決方案:
先確認程式已經標明主鍵模式,然後將資料庫表刪除,重新運行程式,建立帶有主鍵模式的資料表,這樣就可以了,而且資料也成功的插入進去。
Hibernate中Caused by: java.sql.SQLException: Field 'address_id'doesn't have a default value