Reputation: 24635
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
Upvotes: 6
Views: 5610
Reputation: 129
Here is my solution. Applicable for Postgres
<hibernate-mapping>
<!-- ... -->
<database-object>
<create>CREATE SEQUENCE my_sequence</create>
<drop>DROP SEQUENCE IF EXISTS my_sequence</drop>
</database-object>
</hibernate-mapping>
Upvotes: 0
Reputation: 18925
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.
Upvotes: 1
Reputation: 15
-We cant create sequences by using hbm2ddl property -we can create any number of tables any no of times but not sequence
sequence is db specific and we have to create our selves sequence in db
Upvotes: -2
Reputation: 570365
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.
Upvotes: 1