1. 程式人生 > >JPA中could not insert: 的解決辦法

JPA中could not insert: 的解決辦法

報錯如下:
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方法插入資料時,就不會報錯了。