JPA #Id #GeneratedValue annotations vs DB primary key? - jpa

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.

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;

Use Sequence created by Flyway in JPA

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.

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.

JPA 2 #JoinTable with keygeneration

Is there a way in JPA 2 to use a #JoinTable to generate a UUID key for the id of the row? I do not want to create new entity for this table (even if that would solve the problem) and I do not want to create it from the DB.
#ManyToMany
#JoinTable(name="Exams_Questions", schema="relation",
joinColumns = #JoinColumn(name="examId", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="questionId", referencedColumnName = "id"))
private List<Question> questions = new ArrayList<Question>();
db table
CREATE TABLE [relation].[Exams_Questions](
[id] [uniqueidentifier] PRIMARY KEY NOT NULL,
[examId] [uniqueidentifier] NOT NULL,
[questionId] [uniqueidentifier] NOT NULL,
Not sure exactly what the question is, but let me try a response.
For your first sentence alone, I would say "Yes" and "Possibly":
You'll need a separate #Entity class for the Question, and in that class you'd specify the mapping for id.
There is no way using spec JPA to specify auto-generation of a UUID value for a column. There are ways using OpenJPA and Hibernate. EclipseLink will allow you to create a custom generator for this purpose, and their example is, in fact, for a UUID.
If you'd like to expose properties of the join-table OR otherwise have JPA manage them (i.e. the id on the Exams_Questions table), then see this external link (found on this answer). You'll end up with #OneToMany relations from Exam/Question entities to the join table, and #ManyToOne relations from the join table to Exam/Question entities.
Exposing the join table as an entity will let you manage a separate key (uuid). If you don't need the uuid primary key, then don't do this - it's not necessary to solve the problem, as the examId/questionId combination is unique.

JPA: Give a name to a Foreign Key on DB?

I have a simple questions. How can I give a name to the Foreign Key relations that arise from the # ManyToOne annotation ?
With JPA 2.1 you can just do this with the foreignKey annotation:
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#ManyToOne
#JoinColumn(name = "company_id", nullable = false, foreignKey = #ForeignKey(name="FK_COMPANY__ROUTE"))
private Company company;
Do not confuse with the deprecated hibernate equivalent
As of JPA 2.1 it is possible to define foreign keys via #ForeignKey annotation.
Unfortunately, it is not very useful if you only need to change the name. If you specify custom name of the FK, you also have to specify SQL definition of the FK. That is at least the way it works in EclipseLink 2.5.0.
If you are interested in naming the column used in the foreign key, one may specify the name of the column used to create the foreign key, using the #JoinColumn annotation along with the #ManyToOne annotation. The value of the name attribute of the #JoinColumn annotation is used by the JPA provider to map the column name in the table to the entity's attribute.
However, the name of the foreign key constraint created itself cannot be configured. At the time of writing this, it is not possible to specify the name of the foreign key constraint using a JPA annotation or configuration parameter in the OR mapping files. If you need to change the name of the foreign key constraint, then you must create the DDL statement yourself, instead of relying on the JPA provider to do this.
I think #ForeignKey doesn't work with #JoinTables or I don't know how to set custom names by this, I have tried it on #JoinTable->foreignKey and #JoinColumn->foreignKey