JPA overwrite record with auto_increment primary key - java

I've searched but nothing found for me. I have an entity class like this belove:
#Entity
public class Report {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "descrizione")
private String descrizione = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
}
And a table into mysql db with auto_increment pk. But I don't know why the auto_increment works only when I start the web service. Later, hibernate just overwrite the last record without create a new one with the auto incremented primary key.
Into the application.properties I have this configuration:
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/civicsense?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=AAAAAAA
Some help will be appreciated

First, change your int to Long. And you can omit the strategy, since for MySQL GenerationType.IDENTITY is the same as GenerationType.AUTO which is equivalent to just add #GeneratedValue.
#Id #GeneratedValue
private Long id;
Also, your problem might be the way you are adding your entity. You might want to use saveAndFlush() in this case, since changes will be flushed to DB immediately in this command, which might be prevent your issue, because your actual method might not being committing on time.

You need to change:
#GeneratedValue(strategy = GenerationType.IDENTITY)
for
#GeneratedValue(strategy = GenerationType.AUTO)
and in the application.properties use:
spring.jpa.hibernate.ddl-auto=update

Related

Hibernate having issue with generating sequence value with Postgres

I am using hibernate entity and a sequence generator with it.
Database is Postgres and hibernate version is - 5.4.24.Final.
I have a table X with a sequence "seq_x" and below is the hibernate model for it.
#Audited
#Entity
#Table(name = "x")
public class XModel {
private Long id;
private String strCol;
#Id
#Column(name = "id_gen", columnDefinition = "serial")
#GeneratedValue(strategy= GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "str_col")
public String getStrCol() {
return strCol;
}
public void setStrCol(String strCol) {
this.strCol = strCol;
}
}
Now the problem occurs when inserting a value in table X using hibernate model.
Sometimes the insertion fails as i have not explicitly specified the sequence name "seq_x" using #GenericGenerator and hibernate was looking for a default sequence name "x_id_gen_seq". That seems to be a valid behaviour. In this case i see the below query in logs throwing exception:
select currval('x_id_gen_seq')
Now Sometimes, the insertion works and in logs i see
"2022-06-13 11:44:25,431 DEBUG [org.hibernate.id.IdentifierGeneratorHelper] (default task-116) Natively generated identity: 523"
Now, i am literally confused what could be the reason behind it. I tried going through the hibernate source code but could not find much.

Spring data JPA only one composite key is auto incremented issue

I am using MySQL database.
In my table i there are two four primary keys, out of which one is auto incremented.
#Embeddable
public class EmployeeId implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Column(name = "id", nullable = false)//
This is just Pk in mysql table
**private int id;**
// I have tried and #GeneratedValue(strategy = GenerationType.IDENTITY),
#GeneratedValue(strategy = GenerationType.IDENTITY)
//and #GeneratedValue(strategy = GenerationType.TABLE)
//#GeneratedValue(strategy = GenerationType.AUTO, generator = "id") #SequenceGenerator(name = "id", sequenceName = "id")
**this is auto incremented and pk in mysql table**
#Column(name = "gender_key", nullable = false)
private int gender_key;
}
#Entity
#Table(name = "employee")
public class employee {
#EmbeddedId
private EmployeeId employeeId;
private String emp_name;
private String mobile_no;
employee() {
}}
public interface employeeRepository extends
JpaRepository<employee, EmployeeId> {
}
In My Controller I want id after employeeRepository.save(bean); method because i want to save that id in different db .
logger.info("gender_key is --- > "+gender_key);
But I am getting always 0 value of gender_key.
The thing which I have tried is:
bean = employeeRepository.save(bean)
int gender_key= bean.getGender_key();
logger.info("gender_keyis --- > "+gender_key);
But still the value for gender_key is 0(Zero).
Or any Query which I have to write in repository .
How I can get the auto incremented value of gender_key which is inserted into MySQL table?
Please Help.
Thanks in advance.
Your JPA #Id does not need to match the database PK column(s). So long as it is unique then that is all that matters.
From https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing:
The JPA Id does not always have to match the database table primary
key constraint, nor is a primary key or a unique constraint required.
As your an auto-increment column is guaranteed to be unique then just use gender_key as your #ID and map id as a normal column.
#Entity
#Table(name = "employee")
public class employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int genderKey;
#Column
private int id;
}
To be honest I would find your schema confusing however.
I would also suggest reading the following:
https://www.javatpoint.com/java-naming-conventions
You're missing a #GeneratedValue at the id field.
Depending on its values, you're free to choose a strategy for generation, like a sequences, id tables, an automatic internal id generation.
Last but not least GenerationType.AUTO will choose one of the mentioned strategies.
See the Javadocs for javax.persistence.GeneratedValue and javax.persistence.GenerationType.

Exception "org.hibernate.PersistentObjectException" in Hibernate

I use in my project Hibernate. And have error when the server start:
org.hibernate.PersistentObjectException: detached entity passed to persist
Following "autorization" code:
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "login", unique = true, updatable = false)
private String name;
//Important to Hibernate!
#SuppressWarnings("MySQLConfig")
public UsersDataSet() {
}
#SuppressWarnings("MySQLConfig")
public UsersDataSet(long id, String name) {
this.setId(id);
this.setName(name);
}
public UsersDataSet(String name) {
this.setId(-1);
this.setName(name);
}
Please, explain me, where am I wrong?
I'm suspecting that you are trying to do session.persist(userData) rather than doing session.saveOrUpdate(..) (will update the data on the detached object) or session.save(..) (Will create a new row). Please try any of these last two depending on what you want.
Next line to create id automatically. That's why you have an exception.
#GeneratedValue(strategy = GenerationType.IDENTITY)
JPA strategy generated id automatically when saving essence. But the constructor has written
that is necessary to do manually. That's why JPA thinking detached from persistence context.
For fix it you can change direction id or GeneratedValue(strategy = …)
public UsersDataSet(long id, String name) {
// this.setId(id);
this.setName(name);
}

JPA Sequence Generated Value Not Working

I need to use an existing sequence of the db to generate the id of this entity:
#Entity
#Table(schema="sistema", name="clientes_consultas")
public class Consulta implements Serializable {
#Id
#SequenceGenerator(schema = "sistema", sequenceName = "clientes_consultas_id_seq",
name = "seq_c", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_c")
protected Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
This is my sequence, and its stored on a schema that is not the postgres default 'public', its called 'sistema':
Unfortunately, theres an stacktrace saying that the sequence dont exists :(
Any clue?
Your sequence owner is "postgres". Maybe you defined different user than postgres in your connection.

Embeddable PK Object not populating after persist and flush

I have an embedded PK object that doesn't populate the id field after persisting and flushing to the database. The ID is an auto-increment field in the database.
Now normally, I would just try a refresh, but it throws the following error:
"Entity no longer exists in the database: entity.Customers[ customersPK=entity.CustomersPK[ id=0, classesId=36 ] ]."
public class Customers implements Serializable {
#EmbeddedId
protected CustomersPK customersPK;
...
}
#Embeddable
public class CustomersPK implements Serializable {
#Basic(optional = false)
#Column(name = "id")
private int id;
#Basic(optional = false)
#NotNull
#Column(name = "classes_id")
private int classesId;
.....
}
And here's the code that makes the call
Classes cl = em.find(Classes.class, classId);
CustomersPK custPK = new CustomersPK();
custPK.setClassesId(cl.getId());
Customers cust = new Customers(custPK);
em.persist(cust);
em.flush();
// The problem is right here where id always equals 0
int id = cust.getCustomerspk().getId();
Thanks for the help.
Why would the id not be 0, you have never set it?
If it is a generated id, you need to annotate it using #GeneratedValue, otherwise you need to set the value.

Categories

Resources