unknown
unknown

Reputation: 5017

GenerationType.SEQUENCE does not generate sequence in hibernate

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 :-

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

Here CustomSQLDialect is a class which extends 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.

DEBUG IdentifierGeneratorHelper - Natively generated identity: 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.

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

Upvotes: 3

Views: 28867

Answers (5)

Rafael S. Fijalkowski
Rafael S. Fijalkowski

Reputation: 666

Try to use @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.

For more information please visit the documentation.

Upvotes: 0

Deepak
Deepak

Reputation: 1768

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

Upvotes: -1

hide
hide

Reputation: 92

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

Upvotes: 4

Tobias Liefke
Tobias Liefke

Reputation: 9022

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

Upvotes: 3

José Mendes
José Mendes

Reputation: 990

According to Hibernate 4.x documentation we have:

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

For the GeneratorType.AUTO your table must have an 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.

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

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.

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.

Upvotes: 1

Related Questions