Sequence used to increment and ID in Postgresql not called by hibernate - java

I added a sequence MAIL_ID_SEQ to an existing table in Postgresql :
CREATE SEQUENCE MAIL_ID_SEQ START WITH 1;
alter table MAIL alter column ID set default nextval('MAIL_ID_SEQ'::regclass);
alter SEQUENCE MAIL_ID_SEQ owned by MAIL.ID;
The ID exist inside a composite key MailId :
#Embeddable
public class MailId implements Serializable{
#Column(name = "ID")
private int id;
#Column(name = "YEAR")
private int year;
}
I want the ID to be auto_increment using the sequence I created.
The problem is that the value of the ID is always 0 when a new record is inserted from via Hibernate, but when I insert a value directly from the command line (inset into MAIL ..) in the MAIL table, the value of the ID is incremented.

You need to add annotations like this to the id field:
#SequenceGenerator(name = "mail_id_gen", sequenceName = "MAIL_ID_SEQ", allocationSize = 1)
#GeneratedValue(generator = "mail_id_gen")
The generator name must be different for each class. The allocationSize is completely optional, but setting it to 1 is a workaround to a bug in Hibernate 5.0 and 5.1 related to sequences not created by schema export. Another workaround for that bug is to set the hibernate.id.optimizer.pooled.preferred property to NONE in the persistence.xml like this:
<property name="hibernate.id.optimizer.pooled.preferred" value="NONE"/>
If this is not enough and it still tries to insert 0, change the field type from int to Integer and leave it's default to null.

Related

Is it possible to not generate a new primary key value if already set?

I have a situation in which I find the next sequence value (using nextval), set it to a database column and I want to reuse that value as the object's primary key. The problem is that although I triggger save with the correct values, Spring JPA generates another primary key and does not use the one I gave it.
For example, I have an entity:
public class MyEntity implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_MY_ENTITY")
#SequenceGenerator(sequenceName = "SEQ_MY_ENTITY", allocationSize = 1, name = "SEQ_MY_ENTITY")
private Long id;
#Column(name = "field1")
private String field1;
In some business flow, I need to set field1 = id. I do this by:
get next val from dual.
set value to field1
set value to id
Problem is that what is saved for id = field1 + 1. How can I have the two values in sync without calling save with empty field1 and then another save after I've updated field1?
You can use #Id on two columns : id and field1 or use composite key using #Embeddable

How to get the next value in a sequence with #GeneratedValue in spring-jpa

There is already some data available in table, where id being the primary key for me. So when i trying to invoke my spring jpa code to add values to the table i'm using #GeneratedValue for the primary key.
But this way is generating value which is already present in DB. so my application is throwing an exception.
Is there any way i can get the current value from the table and increment my primary key id wrt the previous value of ID present in the table
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id", updatable = false, nullable = false)
private int id;
Let's say your max id in DB currently is 500. Run this:
CREATE SEQUENCE seq_name_in_db START WITH 501;
And change to:
#Id
#SequenceGenerator(name = "some_seq", sequenceName = "seq_name_in_db")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "some_seq")
private int id;
UPDATE: (Solution to OP's comment)
While inserting directly, do this:
INSERT INTO some_table (id, ...) VALUES (seq_name_in_db.NEXTVAL, ...);
When You create the sequence, you can let it start with a certain value e.g.
CREATE SEQUENCE XX_SEQ
START WITH 100
INCREMENT BY 1 ;

Hibernate - Recreating a table and assign primary key from one(beginning)

I am working with PostgreSQL database for a Spring RESTful API. I am using Spring Data, Spring JPA and Hibernate.
To produce a customized primary key, I am using SequenceGenerator. Everything works fine. The problem occurs when I am deleting a table from database and want create it again where the primary key will be again start from 1.
I am deleting a table from database for some reason which will be created again. I am using pgAdmin UI where I am just dropping the table. Next time when I am creating the table again, Hibernate still remembers the last produced primary keys and thus it start producing primary keys from the next number of the last primary key, thus producing a totally different not 1 which I want. I think the reason is, hibernate is storing the record of last produced primary keys though the table has been deleted.
That's why I am looking for help how to force hibernate to start producing primary from from 1 (one) for a newly created table.
In property file, I have the following property:
spring.jpa.hibernate.ddl-auto=update
I tried to by setting the following,
spring.jpa.hibernate.ddl-auto=create
It solved the problem for this table but rest all of tables were also recreated, thus I lost all my data.
This are class for which I am trying to recreate a table.
#Data
#Entity
#Table(name = "professions")
public class Profession extends BasicEntity {
#Id
#Column(name = "profession_id", unique = true)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "profession_key_generator")
#SequenceGenerator(name = "profession_key_generator", allocationSize = 1)
private int profession_id;
#Column(name = "profession_rus_title", unique = true)
private String rusTitle;
#Column(name = "profession_eng_title", unique = true)
private String engTitle;
#Override
public Integer getId() {
return profession_id;
}
public Profession(String rusTitle, String engTitle){
this.rusTitle = rusTitle;
this.engTitle = engTitle;
}
public Profession(){
}
}

Primary key is not starting from 1 after truncating table data

I am using
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
in UserDetails table. But, once I truncate UserDetails table, it is not starting Id value from initial onwards. I didnt give SEQUENCE in db, but it is adding as sequence.
First, When you use #GeneratedValue(strategy = GenerationType.AUTO) annotation the persistence provider will determine values based on the type of the primary key attribute.
This type can be numerical or UUID. For numeric values (Your situation) the generation is based on a sequence or table generator. So the primary key values will be unique at the database level.
Now let's back to your question.
What you can do is that to finding the generated sequence on your database and re-create it.
If you use AUTO, if you using hibernate, it will choose one of the strategies to generate your id. From the Reference:
AUTO - either identity column, sequence or table depending on the
underlying DB.
I added
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_DATA")
#SequenceGenerator(sequenceName = "my_seq", allocationSize = 1, name = "SEQ_DATA")
private int id;
If I am truncating table, I will DROP sequence using, DROP SEQUENCE SEQ_DATA;
Then I will create SEQ_DATA again.
create sequence SEQ_DATA minvalue 1 maxvalue 999999999999999999999
start with 1 increment by 1 cache 20;

jpa hibernate: generation type sequence always inserts 0 into column

I'd like to generate a number like 16857 and have that unique for each entry (note, this column is NOT the primary key). I am using JPA, Hibernate and MySQL.
I tried this:
#Entity
#SequenceGenerator(name = "membernumber_sequence", initialValue = 10000, allocationSize = 1)
public class Member implements Model {
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "membernumber_sequence")
private int membernumber;
}
However, it always inserts 0 into the column. What am I doing wrong?
From the javadoc:
The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.
(emphasis mine)
Use a SQL query to get the next sequence value, and initialize the field explicitely.

Categories

Resources