当前位置:Gxlcms > 数据库问题 > Hibernate中Caused by: java.sql.SQLException: Field 'address_id'doesn't have a default value

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

时间:2021-07-01 10:21:17 帮助过:3人阅读

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 statement

Caused 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

标签:

人气教程排行