44

I am new to hibernate and postgres. Actually I am trying to map potgres database using Hibernate. This is my table stucture in postgresql

CREATE TABLE employee
(
id serial NOT NULL,
firstname character varying(20),
lastname character varying(20),
birth_date date,
cell_phone character varying(15),
CONSTRAINT employee_pkey PRIMARY KEY (id )
)

I am trying to add a record to the database using the following code

 System.out.println("******* WRITE *******");
    Employee empl = new Employee("Jack", "Bauer", new Date(System.currentTimeMillis()), "911");
    empl = save(empl);



 //This is the save function

    private static Employee save(Employee employee) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();

    session.beginTransaction();


    int id = (Integer) session.save(employee);
    employee.setId(id);

    session.getTransaction().commit();

    session.close();

    return employee;
}

When I execute the code I am getting the following error

org.hibernate.HibernateException: Missing sequence or table: hibernate_sequence
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.tcs.com.Hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at org.tcs.com.Hibernate.HibernateUtil.<clinit>(HibernateUtil.java:8)
at org.tcs.com.Hibernate.MainApp.list(MainApp.java:51)
at org.tcs.com.Hibernate.MainApp.main(MainApp.java:17)
Caused by: org.hibernate.HibernateException: Missing sequence or table: hibernate_sequence
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1282)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:498)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1740)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1778)
at org.tcs.com.Hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
... 3 more

I have the sequence called "employee_id_seq" in my database. But I dont know why the database is looking for hibernate_seq. Could someone explain the error and the reason.

Thanks in advance!

Added info

This is my employee class

import java.sql.Date;

public class Employee {

private int id;

private String firstname;

private String lastname;

private Date birthDate;

private String cellphone;

public Employee() {

}

public Employee(String firstname, String lastname, Date birthdate, String phone) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.birthDate = birthdate;
    this.cellphone = phone;

}

public int getId() {
    return id;
}

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

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public Date getBirthDate() {
    return birthDate;
}

public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
}

public String getCellphone() {
    return cellphone;
}

public void setCellphone(String cellphone) {
    this.cellphone = cellphone;
}



}
2
  • I'd say Hibernate doesn't know that you are using sequences. It seems to want to use it's own home-grown (slow) sequence table. There should be some kind of anotation that tells Hibernate that your id column is linked to a sequence. Commented Jan 28, 2013 at 11:55
  • @Lakshmi did you resolve the issue ? Commented Jul 21, 2017 at 1:12

8 Answers 8

43

In your domain or Model object annotate the id field as below and it should work. For me the GenerationType.AUTO failed

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell why the GenerationType.AUTO was failing ?
I will warn everyone that this answer will work but it will come at huge performance penalty for Hibernate. This will make two writes per insertion: One to figure out what the ID will be, and then after that to perform the actual persistence. The real answer is the one provided by @David Lavender
32

You haven't posted the important bit: the Employee class.

But my guess is that your Employee class is using @GeneratedValue() without specifying the sequence to use. So, Hibernate uses its default name: hibernate_sequence.

You can supply a sequence name as part of the GeneratedValue annotation. eg.

@GeneratedValue(strategy=SEQUENCE, generator="employee_id_seq")

4 Comments

I am not using any annotations in my employee class. I have added the employee class in my question now
Same here, I'm only using one GeneratedValue(strategy = GenerationType.AUTO) in the AbstractEntity extended by all 126 entities of my schema. This works just fine on MySQL, H2 and HSQLDB. Now my Oracle schema has one sequence per table, so I guess I need to make a copy paste of all my model entities, for the Oracle case. Sigh...
Depending on your database, you can also specify @Generated(GenerationTime.INSERT) instead
I am using postgres and @GeneratedValue(generator="sequence_name") was enough and worked for the primary keys and their sequences.
14

Simple solution :

create hibernate_sequence table as :

"create sequence <schema>.hibernate_sequence"

1 Comment

This is hilarious :-D 🤣
1

If you encounter this with Spring Boot or Spring boot/Hibernate Migration then potentially you can try the following

Quote:

By default, Hibernate generates key from hibernate_sequence table, we can disable it by setting this hibernate.use-new-id-generator-mappings to false.

application.properties


spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=mkyong
spring.datasource.password=password
spring.jpa.hibernate.use-new-id-generator-mappings=false

1 Comment

FYI: The property hibernate.use-new-id-generator-mappings is deprecated as of spring boot 3/hibernate 6.1: github.com/spring-projects/spring-boot/wiki/…
0

If you don't use annotation you should change YourClass.hbm.xml file.

Your ID section should be:

<id name="id" type="int" column="id">
     <generator class="sequence">
         <param name="sequence">employee_id_seq</param>
     </generator>
</id>

File sample:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="sequence">
             <param name="sequence">employee_id_seq</param>
         </generator>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

Comments

-1

You can do two things. One is to just manually create a blank hibernate_sequence table postgresql. Two, most likely there is a conflict with the user account permissions not allowing grails to create that table.

1 Comment

Specifically the issue here is whether a sequence based strategy is used for generating the id. This is the most performant method, but requires at least a default sequence existing.
-1

Apart from creating the table hibernate_sequence which has a column next_val you can also set quarkus.hibernate-orm.database.generation = drop-and-create. Note this will delete all the record in you database.

Comments

-2

For me, what was causing this error was the wrong version of the MySql.Data library.

I had a version 6.9.6.0 defined in the web.config and yet the actual referenced version was older.

I just commented out :

     <system.data>
      <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
     </DbProviderFactories>
   </system.data>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.