[java] Hibernate-sequence doesn't exist

I tried to upgrade hibernate from 4 to 5 in my project with spring 4.2 version. After this upgrade, I found the following error in my stack trace when I called a method for updating.

10:53:32,185 ERROR TableStructure:149 - could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.hibernate_sequence' doesn't exist 

I changed the auto incremented Id with annotation

@GeneratedValue(strategy=GenerationType.AUTO) 

still the error remains.

This question is related to java spring hibernate

The answer is


This is the reason behind this error:

It will look for how the database that you are using generates ids. For MySql or HSQSL, there are increment fields that automatically increment. In Postgres or Oracle, they use sequence tables. Since you didn't specify a sequence table name, it will look for a sequence table named hibernate_sequence and use it for default. So you probably don't have such a sequence table in your database and now you get that error.


This might be caused by HHH-10876 which got fixed so make sure you update to:

  • Hibernate ORM 5.2.1,
  • Hibernate ORM 5.1.1,
  • Hibernate ORM 5.0.11

When you use

@GeneratedValue(strategy=GenerationType.AUTO)

or

@GeneratedValue which is short hand way of the above, Hibernate starts to decide the best generation strategy for you, in this case it has selected

GenerationType.SEQUENCE as the strategy and that is why it is looking for

schemaName.hibernate_sequence which is a table, for sequence based id generation.

When you use GenerationType.SEQUENCE as the strategy you need to provide the @TableGenerator as follows.

     @Id
     @GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator")
     @TableGenerator(name = "user_table_generator",
                table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE")
     @Column(name = "USER_ID")
     private long userId;

When you set the strategy it the to

@GeneratedValue(strategy = GenerationType.IDENTITY) .

original issue get resolved because then Hibernate stop looking for sequence table.


In my case, replacing all annotations GenerationType.AUTO by GenerationType.SEQUENCE solved the issue.


You can also put :

@GeneratedValue(strategy = GenerationType.IDENTITY)

And let the DateBase manage the incrementation of the primary key:

AUTO_INCREMENT PRIMARY KEY

FYI

If you are using hbm files to define the O/R mapping.

Notice that:

In Hibernate 5, the param name for the sequence name has been changed.

The following setting worked fine in Hibernate 4:

<generator class="sequence">
    <param name="sequence">xxxxxx_seq</param>
</generator>

But in Hibernate 5, the same mapping setting file will cause a "hibernate_sequence doesn't exist" error.

To fix this error, the param name must change to:

<generator class="sequence">
    <param name="sequence_name">xxxxxx_seq</param>
</generator>

This problem wasted me 2, 3 hours.

And somehow, it looks like there are no document about it.

I have to read the source code of org.hibernate.id.enhanced.SequenceStyleGenerator to figure it out


Just in case someone pulls their hair out with this problem like I did today, I couldn't resolve this error until I changed

spring.jpa.hibernate.dll-auto=create

to

spring.jpa.properties.hibernate.hbm2ddl.auto=create

I was getting the same error "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mylocaldb.hibernate_sequence' doesn't exist".

Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings property mentioned by @Eva Mariam in my code like this:

@Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.addAnnotatedClasses(User.class);

        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.id.new_generator_mappings","false");
        return properties;
    }

And it worked like charm.


You can also put :

@GeneratedValue(strategy = GenerationType.IDENTITY)

And let the DateBase manage the incrementation of the primary key:

AUTO_INCREMENT PRIMARY KEY

The above answer helped me.


Run this query

create sequence hibernate_sequence start with 1 increment by 1

If you are using Hibernate version prior to Hibernate5 @GeneratedValue(strategy = GenerationType.IDENTITY) works like a charm. But post Hibernate5 the following fix is necessary.

@Id
@GeneratedValue(strategy= GenerationType.AUTO,generator="native")
@GenericGenerator(name = "native",strategy = "native")
private Long id;

DDL

`id` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY

REASON

Excerpt from hibernate-issue

Currently, if the hibernate.id.new_generator_mappings is set to false, @GeneratedValue(strategy = GenerationType.AUTO) is mapped to native. If this property is true (which is the defult value in 5.x), the @GeneratedValue(strategy = GenerationType.AUTO) is always mapped to SequenceStyleGenerator.

For this reason, on any database that does not support sequences natively (e.g. MySQL) we are going to use the TABLE generator instead of IDENTITY.

However, TABLE generator, although more portable, uses a separate transaction every time a value is being fetched from the database. In fact, even if the IDENTITY disables JDBC batch updates and the TABLE generator uses the pooled optimizer, the IDENTITY still scales better.


I added Hibernate sequence in postgres. Run this query in PostGres Editor:

    CREATE SEQUENCE hibernate_sequence
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 2
  CACHE 1;
ALTER TABLE hibernate_sequence
  OWNER TO postgres;

I will find out the pros/cons of using the query but for someone who need help can use this.


in hibernate 5.x, you should add set hibernate.id.new_generator_mappings to false in hibernate.cfg.xml

<session-factory>
    ......
    <property name="show_sql">1</property>
    <property name="hibernate.id.new_generator_mappings">false</property>
     ......
 </session-factory>

Working with Spring Boot

Solution

Put the string below in .application.properties

spring.jpa.properties.hibernate.id.new_generator_mappings=false

Explanation

On Hibernate 4.X this attribute defaults to true.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query