Hibernate中Caused by: java.sql.SQLException: Field 'address_id'doesn't have a default value

來源:互聯網
上載者:User

標籤:

在學習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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.