java GenerationType.SEQUENCE 在休眠状态下不生成序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32719662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:40:18  来源:igfitidea点击:

GenerationType.SEQUENCE does not generate sequence in hibernate

javahibernatejpasql-server-2012sequence

提问by unknown

This is my entity file :-

这是我的实体文件:-

@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;

}

I have tried GenerationType.SEQUENCE& GenerationType.AUTO.
But in case of GenerationType.SEQUENCE, it gives me an error :-

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

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1239) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:120) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:855) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844) at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564) ... 42 more Caused by: org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.alstom.autofie.entity.ArticleFonctionInstructionStatuts] at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:123) at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:213) at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:323) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852) ... 50 more Caused by: org.hibernate.MappingException: com.alstom.autofie2.dao.CustomSQLDialect does not support sequences at org.hibernate.dialect.Dialect.getSequenceNextValString(Dialect.java:882) at org.hibernate.id.SequenceGenerator.configure(SequenceGenerator.java:110) at org.hibernate.id.SequenceHiLoGenerator.configure(SequenceHiLoGenerator.java:55) at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:117) ... 54 more

引起:javax.persistence.PersistenceException: [PersistenceUnit: default] 无法在 org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1239) 在 org.hibernate.jpa.boot.internal 构建 Hibernate SessionFactory .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) 在 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.createNativeContainerEntityManagerFactoryBean.createNativeEntityManagerFactoryBean.createNativeEntityManagerFactory() .springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627) 在 org.springframework.beans.factory.support. .initializeBean(AbstractAutowireCapableBeanFactory.java:1564) ... 42 更多 引起:org.hibernate。MappingException:无法在 org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:123) 在 org.hibernate.mapping. 实例化 id 生成器 [entity-name=com.alstom.autofie.entity.ArticleFonctionInstructionStatuts]。 SimpleValue.createIdentifierGenerator(SimpleValue.java:213) at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:323) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859) at 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(方言。java:882) 在 org.hibernate.id.SequenceGenerator.configure(SequenceGenerator.java:110) 在 org.hibernate.id.SequenceHiLoGenerator.configure(SequenceHiLoGenerator.java:55) 在 org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory .createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:117) ... 54 更多

Here CustomSQLDialect is a class which extends SQLServerDialect.

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

In case of GenerationType.AUTO, it gives me an error while inserting multiple records because it generates same key all the time, not sequential key.

在 的情况下GenerationType.AUTO,它在插入多条记录时给我一个错误,因为它一直生成相同的键,而不是顺序键。

DEBUG IdentifierGeneratorHelper - Natively generated identity: 0

DEBUG IdentifierGeneratorHelper - 本机生成的身份:0

I have verified in sql server, AFIS_Sequence is generating sequence each and every time. That means there is some issues with hibernate configuration.

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

Is there any configuration missed or is it a bug of hibernate ?

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

采纳答案by Tobias Liefke

CustomSQLDialectshould extend SQLServer2012Dialect, as previous versions didn't support sequences.

CustomSQLDialect应该扩展SQLServer2012Dialect,因为以前的版本不支持序列。

回答by hide

When you use

当你使用

@GeneratedValue(strategy=GenerationType.AUTO)

You are using the auto increment that have hibernate, but if you use

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

@GeneratedValue(strategy=GenerationType.IDENTITY)

You will use the auto increment of your data base

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

回答by José Mendes

According to Hibernate 4.x documentation we have:

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

GeneratorType.AUTO This is the default strategy and is portable across different databases. Hibernate chooses the appropriate ID based on the database.

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

For the GeneratorType.AUTOyour table must have an Auto Incremented Primary Key.

对于GeneratorType.AUTO您的表必须有一个Auto Incremented Primary Key.

We have also:

我们还有:

GeneratorType.SEQUENCE Some databases provide a mechanism of sequenced numbers, so this setting will let Hibernate use the sequence number.

GeneratorType.SEQUENCE 一些数据库提供了序列号的机制,所以这个设置会让 Hibernate 使用序列号。

What I can see is that you didn't specify correctly which sequente Hibernate should use, follow this example:

我可以看到的是,您没有正确指定应该使用哪个序列 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;
...
}

You need to create a Sequence in your Database and specify it to your bean.

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

Edit:

编辑:

I am adding more information:

我正在添加更多信息:

The strategy is defined as a SEQUENCE, and accordingly the generator is given a reference to a sequence generator, empSeqGen, which refers to a sequence object in the database. Using the @SequenceGenerator, we reference EMP_SEQ_GEN, which is a sequence object created in the database.

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

回答by Rafael S. Fijalkowski

Try to use @GeneratedValue(strategy=GenerationType.IDENTITY).

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

But I recomment to understand what each one do:

但我建议了解每个人的作用:

  • AUTO: Indicates that the persistence provider should pick an appropriate strategy for the particular database.
  • IDENTITY: Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
  • SEQUENCE: Indicates that the persistence provider must assign primary keys for the entity using a database sequence.
  • TABLE: Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
  • AUTO:表示持久化提供者应该为特定的数据库选择合适的策略。
  • IDENTITY:指示持久性提供程序必须使用数据库标识列为实体分配主键。
  • SEQUENCE:指示持久性提供程序必须使用数据库序列为实体分配主键。
  • TABLE:指示持久性提供程序必须使用底层数据库表为实体分配主键以确保唯一性。

For more information please visit the documentation.

有关更多信息,请访问文档

回答by Deepak

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();
    }
}
}