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.
Related
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;
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.
I have a new table in my DB which simply aggregates some data which I don't want to hold as a reference in any of my entities. Because of above I don't have an entity of that type in my application. Now the problems starts when I want to create simple query from that table. We use named queries and criteria api in our application as a standard. Since my query is simple and is going to be asked a lot of times the perfect solution would be to use JPQL and named query. But how might I achieve this without having an entity related to this table... As far as I remember there is COLUMN('xxx') expression which can be used to obtain column which isn't used in entity, so maybe there is something similar to do the trick with whole table?
So let me recap, because It's possible that You may have a problem to understand me well :)
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
#Entity
public class Pet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
Let's say that besides above two tables I have third one which I don't want to use neither in Pet nor in Person. So:
CREATE TABLE ANY_OTHER_TABLE(
PERSON_ID BIGINT NOT NULL,
PET_ID BIGINT NOT NULL
);
So now question is how should JPQL look like to produce SQL like this:
SELECT * FROM ANY_OTHER_TABLE WHERE PET_ID = 1;
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.
The JPA specification gives the following explanation of the annotation #GeneratedValue(strategy=TABLE):
The TABLE generator type value indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
But what does "using an underlying database table" mean in practice? Does it mean using an auxiliary table? Or by scanning the entity-table to find an ID not in use? Or something else?
Check out JavaDoc for TableGenerator, it has a nice example of how it works:
Example 1:
#Entity public class Employee {
...
#TableGenerator(
name="empGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="EMP_ID",
allocationSize=1)
#Id
#GeneratedValue(strategy=TABLE, generator="empGen")
int id;
...
}
Example 2:
#Entity public class Address {
...
#TableGenerator(
name="addressGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ADDR_ID")
#Id
#GeneratedValue(strategy=TABLE, generator="addressGen")
int id;
...
}
Basically ID_GEN is an internal (non-business) table of key-value pairs. Every time JPA wants to generate ID it queries that database:
SELECT GEN_VALUE
FROM ID_GEN
WHERE GEN_KEY = ...
and incremenets the GEN_VALUE column. This mechanism can be used to emulate sequences or to take even further control of generated ids.
In the case of EclipseLink, it uses an auxiliary table. The documentation says
By default, EclipseLink chooses the TABLE strategy using a table named SEQUENCE, with SEQ_NAME and SEQ_COUNT columns