报错如下:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not insert: [com.zj.bean.Person]
- persistence.xml:
<?xml version="1.0" encoding="utf-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="mysqlJPA" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="123" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sys" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
- Person.java
package com.zj.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
private int id;
private String name;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(length=12)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在项目中,我所使用的jpa的provider是hibernate框架,数据库连接的是mysql。这里报错的原因是因为:
我们在数据库中创建person表的时候,没有设置表的id属性是自增长的,因此,只要修改下person表:
alter table person modify id int auto_increment;
然后在运行时,persist方法插入数据时,就不会报错了。