【问题标题】:Why is JPA-Hibernate unable to generate an identifier for an object while persisting?为什么 JPA-Hibernate 在持久化时无法为对象生成标识符?
【发布时间】:2018-05-27 02:31:38
【问题描述】:

考虑sn-p-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <description>nes dao context configuration.</description>

    <!-- JPA Configuration -->
    <tx:annotation-driven />

    <!-- UAT -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="org.postgresql.Driver" />
        <property name="jdbcUrl"
            value="jdbc:postgresql://localhost:5432/postgres" />
        <property name="properties">
            <props>
                <prop key="c3p0.acquire_increment">5</prop>
                <prop key="c3p0.maxStatementsPerConnection">20</prop>
                <prop key="c3p0.maxStatements ">100</prop>
                <prop key="c3p0.maxPoolSize">500</prop>
                <prop key="c3p0.max_statements">0</prop>
                <prop key="c3p0.minPoolSize">5</prop>
                <prop key="user">postgres</prop>
                <prop key="password">system</prop>
            </props>
        </property>
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <!-- <property name="generateDdl" value="true" /> -->
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
            </bean>
        </property>
        <property name="persistenceUnitName" value="" />
        <property name="persistenceUnitManager">
            <bean
                class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
                <property name="defaultDataSource" ref="dataSource" />
            </bean>
        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
        p:dataSource-ref="dataSource" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
    </bean>

</beans>

使用 DAO 层-

/** The entity manager. */
@PersistenceContext
private EntityManager entityManager;


@Transactional
public void saveEmployee(){
    Employee employee = new Employee();
    employee.setName("Some Name");
    employee.setAddress("Some Address");
    employee.setDesignation("Java EE Technologist");

    entityManager.persist(employee);
}

在日志中显示-

org.postgresql.util.PSQLException: 错误: 列中的空值 “employee_id”违反了非空约束

Entity class being-
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 3243984159882700015L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "EMPLOYEE_ID")
    public long id;

    // other columns

}

在 PostgreSQL 端创建的表作为-

CREATE TABLE employee
(
  employee_id integer NOT NULL,
  employee_name text NOT NULL,
  employee_address text NOT NULL,
  designation text NOT NULL,
  CONSTRAINT employee_pkey PRIMARY KEY (employee_id)
)

请提出建议。

【问题讨论】:

  • 您应该在创建表脚本中定义employee_id SERIAL 以便让dbms 处理id 生成。
  • 您可能需要将employee_id设置为序列类型或使用序列来生成身份。

标签: spring postgresql hibernate jpa


【解决方案1】:

它适用于 Postgresql 端的自定义序列-

CREATE SEQUENCE employee_id_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;

id 列注释为-

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_id_seq")
@SequenceGenerator(name = "employee_id_seq", sequenceName = "employee_id_seq", allocationSize = 1)
@Column(name = "EMPLOYEE_ID", unique = true, nullable = false)
public long id;

【讨论】:

  • Postgresql 使用 JPA 自动生成主键时存在问题,因为它使用序列生成器。这可能是解决此问题的方法。
  • 如果你使用ALTER TABLE employee ALTER COLUMN employee_id SET DEFAULT nextval('employee_id_seq'::regclass),你仍然可以使用strategy = GenerationType.IDENTITY
猜你喜欢
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多