Use Sequence created by Flyway in JPA - postgresql

I'm using a Spring Boot 2 / Flyway / Postgres setup.
I want to achieve to let Flyway create a table with a sequence for automatic key iteration. JPA should recognize the sequence and use it.
I let Flyway execute a PostgreSQL script:
CREATE SEQUENCE config_id_seq;
CREATE TABLE config
(
ID BIGINT NOT NULL PRIMARY KEY DEFAULT nextval('config_id_seq'),
DESCRIPTION VARCHAR(500)
);
And this is the Entity definition:
#Entity
#Table(name = "config")
public class Config {
#Id
#SequenceGenerator(name = "config_id_sequence", sequenceName = "config_id_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "config_id_sequence")
#Column(name = "id")
private long id;
#Column(name = "description")
private String description;
On start up the following errors are thrown:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "config_id_seq" already exists
Caused by: org.postgresql.util.PSQLException: ERROR: cannot change sequence "config_id_seq"
My interpretation is that Flyway successfully executed the script and created a sequence. But JPA wants to create the sequence afterwards and fails because it already exists. Please, correct me if I'm wrong here.
Now how can I configure JPA to reuse the existing sequence, if this is possible?

We need to set spring.jpa.hibernate.ddl-auto property to none or you can skip this property so that spring does not create database objects on its own.
If we are using a flyway then we should give the responsibility of database objects creation to flyway only i.e create all database objects with flyway scripts only like tables and sequence.
Specifying GeneratedValue says for JPA to use a sequence, retrieve the next value itself, and then use that in the INSERT.
But make sure you have the same configuration that you mentioned on entity class and flyway script.

Related

"hibernate_sequence" does not exist"

I am getting "ERROR: relation "hibernate_sequence" does not exist" exception while doing insert operation.
Technical Stack
-> Springboot
-> Hibernate
-> PostgreSQL
Approaches tried so far.
-> Verified all entity classes in project, generation strategy is used as "#GeneratedValue(strategy = GenerationType.IDENTITY)".
-> Verified database tables, pk is either Serial or Int with proper sequence generated value.
-> Tried with use-new-id-generator-mappings property as false, didn't worked.
-> Verified sequence with name "hibernate_sequence" is available in Database.
Analysis so far
-> Entities those are annotated with #Audited having this issue as hibernate envers expect global "hibernate_sequence". But not able to find the exact solution.
Note : This was working few days back without any issue, Since last week started getting this issue.
As you said, hibernate-envers is looking for the hibernate_sequence.
Its used to insert records into the REVINFO table
Assuming spring.jpa.hibernate.ddl-auto is not set to create
either
create a hibernate_sequence manually
create a sequence with the name you want. e.g rev_id_seq. Then override the REVINFO definition to change the sequence name by adding your definition of the RevisionEntity
#Entity
#RevisionEntity
public class MyRevision implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rev_id_generator")
#SequenceGenerator(name = "rev_id_generator", sequenceName = "rev_id_seq", allocationSize = 1)
#RevisionNumber
private int id;
#RevisionTimestamp
private long timestamp;
// Getters, setters, equals, hashCode ...
}
https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#envers-tracking-modified-entities-revchanges
https://thorben-janssen.com/hibernate-envers-extend-standard-revision/
Initially set the spring.jpa.hibernate.ddl-auto to create for the first time and run the application. It will create the hibernate sequence. after that change spring.jpa.hibernate.ddl-auto to none. It will prevent any further data loss from tables. Or you can set to update if necessary.
Because you are using #GeneratedValue()
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.
I Also got this working using;
#GeneratedValue(strategy = GenerationType.IDENTITY)
I faced the exact same issue when I migrated from Maria to Postgres. Either/both problems one may have:
Schema name is not in the connection URL
If the schema name isn't passed flyway_schema_history table and sequences were created under the public schema. And application tables were made under the custom schema.
So make sure you have the required schema configured.
spring:
datasource:
url: jdbc:postgresql://localhost:5432/platform?currentSchema=product1
username: admin
password: admin
driver-class-name: org.postgresql.Driver
flyway:
schemas:
- product1
Sequence got created but with another name
This was the problem for me. Sequence got created with the name revinfo_rev_seq. However, while inserting the records it was looking for hibernate_sequence.
I added another revision under flyway migration to rename the already created sequence.
-- This is not required for MySQL/MariaDB. However, while using PostgresSQL getting the error -> ERROR: relation "hibernate_sequence" does not exist
ALTER SEQUENCE revinfo_rev_seq RENAME TO hibernate_sequence;

Postgres Partitioning not working with hibernate if id is bigserial

I have partitioned my table in Postgres. So there are 2 tables now :
Base table users , with no primary key but using a sequence generator for id column : nextval('users_id_seq'::regclass)
Child table inheriting users
CREATE TABLE users_part_2019_01 (
CHECK (createdon >= '2019-01-01 00:00:00'
AND createdon < '2019-02-01 00:00:00')
) INHERITS (users);
ALTER TABLE users_part_2019_01 ADD CONSTRAINT users1_pkey PRIMARY KEY (id);
I am inserting data into users table using jpa. In the data model I have used :
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Getting the following error :
"org.springframework.orm.jpa.JpaSystemException: The database returned
no natively generated identity value; nested exception is
org.hibernate.HibernateException: The database returned no natively
generated identity value
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)"
It is working as expected independently with postgres.
Got the solution. Instead of GenerationType.IDENTITY, GenerationType.AUTO is working
In case you are coming here from spring boot (2.2.x +) and using postgresql partitioning, the accepted answer alone is not enough to make it work. Hibernate, in this case, will throw the following:
Schema-validation: missing sequence [schema_name.hibernate_sequence]
In this case, the hibernate simply wants you to provide the identity generator for the sequence field by passing it as:
#GeneratedValue(strategy = GenerationType.AUTO, generator = "schema_name.generator_sequence_name_seq")

JPA #Id #GeneratedValue annotations vs DB primary key?

I have an app accessing an existing MySQL DB utilizing JDBC and am converting to JPA. My DB is already setup with primary keys which are auto generated. Do I need to annotate my entity classes w/ #Id, #GeneratedValue... when this is already defined in the DB? Will the annotations override / conflict with the DB primary key / indexes already defined?
It not going to conflict with the DB primary key and the JPA annotations.Since primary key is already indexed, it's not a problem at all.
You should add annotations in entity classes.It is not going to conflict with already defined DB.If you deploy the system in new DB environment then annotations must be needed.
I assume you are using autonumbers in MySQL and these are autogenerated.
The following code will do what you require:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "table_id")
Notice the GenerationType.IDENTITY strategy? This tells JPA to use the autogenerated database values.

JPA create object by id

I have a following JPA entity:
#Entity
#Table(name = "sessions")
public class Session extends BaseEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
#JoinColumn(name = "user_id")
private User user;
...
}
In order to insert new Session object into database I need to perform a following steps:
Select user from db
Create new Session object, set user to this session object and then invoke sessionRepository.save(session)
Is it possible to avoid step #1 in case I know user_id ? I don't want to make redundant select to my database when possible.
Use EntityManager.getReference() instead of EntityManager.find() (in Spring-data-jpa crud repositories, this operation is named getOne()).
This returns a lazy, uninitialized User proxy, without executing any SQL query. Of course, you'd better have a foreign key constraint in the database to make sure the insert fails if you try to insert a new Session for an unexisting user.
There is an API that you can use for this.
If you use JPA, you can use entityManager.getReference() for loading user. This will not make a call to the database, unless you do something with the resulting instance.
A Hibernate equivalent for this is session.load(), which behaves in the same way.

Saving an entity without fetching ID

I have a table T1(ID AUTOINCREMENT INT, COL1, COL2, etc).
The JPA Entity for T1 has a field ID which has been marked as #Generated and #Id. This is to tell JPA that the key of the entity is not set by the application and that the DB will be generating the ID.
The code invokes the persist method to save the entity. I do not need the entity to be managed.
#Entity
#Table(name = "T1")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Long customerd;
#Column(name = "COL1")
private String col1;
When I run the application, JPA seems to INSERT the row in the table and immediately SELECT the generated ID to be set in the object.
Is it possible to tell JPA not to fetch the generated ID? I want JPA to perform the INSERT and forget the record.
The database is DB2. The JPA implementation is Hibernate.
Regards,
Yash
Per JPA Spec, every entity must have a primary key - can be simple or composite primary key. That means you have to specify at least a property to indicate it is the primary key of your entity by using #Id or #EmbeddedId annotations. JPA provider will ensure that the entity's generated id will be available in the Id annotated property during the persist call. The JPA provider will assign the Id either before or after the transaction has committed (depends of the generation strategy used). Regardless of strategy used and unless you manually set the Id property yourself, that won't prevent the JPA provider from querying the generated Id and assigning it to your Entity.