GenerationType.SEQUENCE不会在休眠

时间:2015-09-22 14:30:43

标签: java hibernate jpa sql-server-2012 sequence

这是我的实体档案: -

@Entity
@Table(name = "tbl_article_function_instruction_status")
@XmlRootElement

public class ArticleFonctionInstructionStatuts extends BaseEntity implements Serializable
{
    private static final long                                   serialVersionUID    = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AFIS_Sequence")
    @SequenceGenerator(allocationSize = 5000, name="AFIS_Sequence", sequenceName="AFIS_Sequence")
    @Basic(optional = false)
    @Column(name = "art_fun_ins_status_id")
    private Integer                                             afiStaIndex;

    @Basic(optional = false)
    @Column(name = "art_fun_ins_status_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date                                                afiStaDate;

}

我试过GenerationType.SEQUENCE& GenerationType.AUTO
但是在GenerationType.SEQUENCE的情况下,它给了我一个错误: -

  

引起:javax.persistence.PersistenceException:[PersistenceUnit:default]无法构建Hibernate SessionFactory       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1239)       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access $ 600(EntityManagerFactoryBuilderImpl.java:120)       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl $ 4.perform(EntityManagerFactoryBuilderImpl.java:855)       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl $ 4.perform(EntityManagerFactoryBuilderImpl.java:845)       at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)       在org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)       在org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)       在org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)       ......还有42个   引起:org.hibernate.MappingException:无法实例化id生成器[entity-name = com.alstom.autofie.entity.ArticleFonctionInstructionStatuts]       at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:123)       在org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:213)       在org.hibernate.internal.SessionFactoryImpl。(SessionFactoryImpl.java:323)       在org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)       在org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl $ 4.perform(EntityManagerFactoryBuilderImpl.java:852)       ......还有50个   引起:org.hibernate.MappingException:com.alstom.autofie2.dao.CustomSQLDialect不支持序列       在org.hibernate.dialect.Dialect.getSequenceNextValString(Dialect.java:882)       在org.hibernate.id.SequenceGenerator.configure(SequenceGenerator.java:110)       在org.hibernate.id.SequenceHiLoGenerator.configure(SequenceHiLoGenerator.java:55)       at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:117)       ... 54更多

这里CustomSQLDialect是一个扩展SQLServerDialect的类。

如果是GenerationType.AUTO,它会在插入多个记录时给出错误,因为它始终生成相同的密钥,而不是顺序密钥。

  

DEBUG IdentifierGeneratorHelper - 本机生成的标识:0

我已经在sql server中验证过,AFIS_Sequence每次都会生成序列。这意味着hibernate配置存在一些问题。

是否遗漏了配置或是否是休眠的错误?

5 个答案:

答案 0 :(得分:4)

使用时

@GeneratedValue(strategy=GenerationType.AUTO)

您正在使用具有休眠功能的自动增量,但如果您使用

@GeneratedValue(strategy=GenerationType.IDENTITY)

您将使用数据库的自动增量

答案 1 :(得分:2)

MyActionButton.setMainAction(some function reference here) 应该扩展CustomSQLDialect,因为以前的版本不支持序列。

答案 2 :(得分:1)

根据Hibernate 4.x文档,我们有:

  

GeneratorType.AUTO   这是默认策略,可跨不同数据库移植。过冬   根据数据库选择适当的ID。

对于GeneratorType.AUTO,您的表格必须有Auto Incremented Primary Key

我们还有:

  

GeneratorType.SEQUENCE   有些数据库提供了序列号的机制,因此这个设置将允许   Hibernate使用序列号。

我可以看到你没有正确指定Hibernate应该使用哪个序列,请遵循以下示例:

public class Employee {
@Id
@Column(name="EMPLOYEE_ID")
@GeneratedValue (strategy= GenerationType.SEQUENCE, generator="empSeqGen")
@SequenceGenerator(name = "empSeqGen", sequenceName = "EMP_SEQ_GEN")
private int employeeId =0;
...
}

您需要在数据库中创建一个Sequence并将其指定给您的bean。

编辑:

我正在添加更多信息:

  

该策略被定义为SEQUENCE,因此生成器被赋予参考   到序列生成器empSeqGen,它引用数据库中的序列对象。   使用@SequenceGenerator,我们引用EMP_SEQ_GEN,它是一个序列对象   在数据库中创建。

答案 3 :(得分:0)

尝试使用@GeneratedValue(strategy=GenerationType.IDENTITY)

但是我建议您了解每个人的工作:

  • 自动:表示持久性提供程序应选择一个 特定数据库的适当策略。
  • IDENTITY :表示持久性提供程序必须分配主要 使用数据库标识列的实体密钥。
  • SEQUENCE :表示持久性提供程序必须分配主 使用数据库序列的实体密钥。
  • TABLE :表示持久性提供程序必须分配主 使用基础数据库表确保实体的键 唯一性。

有关更多信息,请访问documentation

答案 4 :(得分:-1)

import java.util.Date;
import javax.persistence.*;

@Entity
@Table(name="driver_license")
public class DriverLicense extends License {
private String driverLicenseName;
 @Temporal(TemporalType.DATE)
 private Date driverLicenseExpiryDate;
 @Temporal(TemporalType.DATE)
 private Date driverLicenseIssueDate;


public String getDriverLicenseName() {
    return driverLicenseName;
}
public void setDriverLicenseName(String driverLicenseName) {
    this.driverLicenseName = driverLicenseName;
}
public Date getDriverLicenseExpiryDate() {
    return driverLicenseExpiryDate;
}
public void setDriverLicenseExpiryDate(Date driverLicenseExpiryDate) {
    this.driverLicenseExpiryDate = driverLicenseExpiryDate;
}
public Date getDriverLicenseIssueDate() {
    return driverLicenseIssueDate;
}
public void setDriverLicenseIssueDate(Date driverLicenseIssueDate) {
    this.driverLicenseIssueDate = driverLicenseIssueDate;
}
}


import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.SequenceGenerator;

@MappedSuperclass
public class License {

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="license_gen")
@SequenceGenerator(name="license_gen",sequenceName="lic_seq_gen",initialValue=1,allocationSize=1)
protected int id;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}
}


import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static SessionFactory sessionFactory ;
static{
    Configuration configuration=new Configuration();
     configuration.addAnnotatedClass(DriverLicense.class);
    // configuration.addAnnotatedClass(DriverLicense.class);
    configuration.setProperty("connection.driver_class","org.postgresql.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/test");                                
    configuration.setProperty("hibernate.connection.username", "postgres");     
    configuration.setProperty("hibernate.connection.password", "postgres");
    configuration.setProperty("dialect", "org.hibernate.dialect.PostgreSQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


    StandardServiceRegistryBuilder registry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory=configuration.buildSessionFactory(registry.build());

}

 public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}



public class Main {

public static void main(String[] args) {

    DriverLicense driverLicense=new DriverLicense();

    driverLicense.setDriverLicenseExpiryDate(new Date());
    driverLicense.setDriverLicenseName("License for all");
    driverLicense.setDriverLicenseIssueDate(new Date());

    Session session=HibernateUtil.getSessionFactory().openSession();

    try {
        session.beginTransaction();

        session.save(driverLicense);

        session.getTransaction().commit();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}