I want to create my database tables automatically with Hibernate and Postgresql, but I get errors about sequences. Is it possible to auto create sequences too with Hibernate, or do I have generate sequences manually?
Example of my entity:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(uniqueConstraints = { @UniqueConstraint( columnNames = { "id" }) })
@SequenceGenerator(name="SEQ_EXAMPLE_ID", sequenceName="example_id_seq", allocationSize=1)
public class Example {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_EXAMPLE_ID")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String g
}
Hibernate config:
hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
Exceptions:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not get next sequence value
org.postgresql.util.PSQLException: ERROR: relation "example_id_seq" does not exist
Hibernate can create table, hibernate sequence and tables used for many-to-many mapping on your behalf but you have to explicitly configure it by calling setProperty("hibernate. hbm2ddl. auto", "create") of Configuration object.
hibernate.hbm2ddl.auto. Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop , the database schema will be dropped when the SessionFactory is closed explicitly.
By default, Hibernate generates key from hibernate_sequence table, we can disable it by setting this hibernate. use-new-id-generator-mappings to false.
spring. jpa. hibernate. ddl-auto (enum) is a Hibernate feature that controls the behavior in a more fine-grained way.
Your mapping seems correct and I suggest activating logging of the following category to see what is happening exactly:
org.hibernate.tool.hbm2ddl
: Log all SQL DDL statements as they are executed
Set it to DEBUG
and check the DDL statements (maybe update the question with the relevant parts).
PS: An allocationSize=1
is not very wise, using the default would be better. But that's unrelated.
You have to enable automatic schema creation in application.properties
as described in Hibernate docs:
hibernate.hbm2ddl.auto = create
or when using Spring:
spring.jpa.hibernate.ddl-auto = create
But the general recommendation is not to use this in production, see Hibernate: hbm2ddl.auto=update in production?
Use database schema migration tools like Liquibase or Flyway instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With