spring data JPA: primary key not sequentially auto increamenting - postgresql

In spring data jpa Application I created one model with #entity annotation. I am saving that model data into table. I am auto incrementing primary key. But when I am saving data into table it's not sequentially auto incrementing.
#GeneratedValue(strategy = GenerationType.AUTO)
class file
#Entity
#Table(name="exception")
public class Exception implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "exception_seq_generator")
#SequenceGenerator(name = "exception_seq_generator", sequenceName = "exception_seq")
#Column(name="exception_id")
public Integer exceptionId;
#Column(name="status_code")
public Integer statusCode;
public String message;
public String status;
public String error;
//Getter and setter
Table
can any one tell me why primary key is not auto incrementing sequentially? why it's not taking 2,3,4.....

First of all try setting the allocationSize:
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "exception_seq_generator")
#SequenceGenerator(name = "exception_seq_generator", sequenceName = "exception_seq", allocationSize=1)
#Column(name="exception_id")
public Integer exceptionId;
Also check your current Sequence in the Database, it might have a wrong value now.
Simpler aproach:
Define the primary-key column in PostgreSQL DB as SERIAL:
CREATE TABLE xy (
id SERIAL PRIMARY KEY;
);
And annotate the Column with:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
The SERIAL type, creates an auto-increment sequence for you and you don't have that much overhead in you JPA Entities.

Related

Spring Data Jpa OneToMany save bidirectional

I have a problem with saving child entities.
Here is my example. My model classes look like this:
#Entity
public class ImportDocument {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private boolean imported;
#Transient
private Status status;
#Basic
private char statusValue;
#OneToMany(mappedBy = "importDocument" , cascade = {CascadeType.ALL})
private List<ImportDocumentItem> importDocumentItems;
}
#Entity
public class ImportDocumentItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "import_document_id")
#JsonIgnore
private ImportDocument importDocument;
}
I have implemented JpaRepository interfaces for both domain classes.
I try to save with:
importDocumentRepository.save(importDocument);
When I save ImportDocument object, everything is inserted. But the problem is that, the import_document_item.import_document_id (which is foreign key of import_document_id) attribute is filled with null value, not with id of import_document that I expected. How can I fix this issue?
Thanks a lot.
You have to set entity relations on both side before saving. Here an example
ImportDocument importDocument = new ImportDocument();
//...
importDocument.setImportDocumentItems(items);
items.forEach(ImportDocumentItem::setImportDocument);
importDocumentRepository.save(importDocument);

JPA entity sequence generating

In spring boot JPA I tried to implement sequence generator but it is not working.
the following is my entity
#Entity
#Table(name = "role_level")
public class RoleLevel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "role_level_sequence", sequenceName = "role_level_id_seq",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "role_level_sequence")
#Column(name = "id", updatable = false)
private Long id;
#Column(name = "role_level")
private String roleLevel;
#Column(name = "role_level_description")
private String roleLevelDescription;
//getters and setters
}
when I insert value in directly through the database then next sequence from the db is not getting in jpa.it shows
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "role_level_pkey"
Detail: Key (id)=(7) already exists.
But the console shows
Hibernate: select nextval ('role_level_id_seq')
I think its not working.
Is there any solution for this.?

JPA Spring Boot postgresql : Insert data with the last ID

I have a MyClass entity with an auto increment id at the time of the project deployment I have an init.sql file to initialize the MY_CLASS table by adding two lines
the problem when I use my web service REST to insert a new line in the MY_CLASS table I have an error message of duplicate key of id 1 for the first click and id 2 on the second click but after the POST goes without problems. To solve this problem I can add the following line in my init.sql file
ALTER SEQUENCE MY_CLASS_id_seq RESTART WITH 3;
My question: How can I configure my POST to persist the data with the last id because whenever I can insert data with SQL.
#Entity
#Cacheable
#Getter
#Setter
#Table(name = "MY_CLASS")
public class MyClass {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String label;
}
#RepositoryRestResource(collectionResourceRel = "clazz", path = "clazz")
public interface MyClassRepository extends PagingAndSortingRepository<MyClass, Long> {
}
init.sql
INSERT INTO public.MY_CLASS (label) values('label_1');
INSERT INTO public.MY_CLASS (label) values('label_2');
Wouldn't you use the sequence generator, would you?
public class MyClass {
public static final String SEQUENCE_NAME = "MY_CLASS_id_seq";
#Id
#GeneratedValue(strategy = SEQUENCE, generator = SEQUENCE_NAME)
#SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME)
private Long id;
#NotNull
private String label;
}

Getting Identity-Generated primary key from JPA

I'm using Netbeans 8.1, Java EE 7, and MS SQL Server. The application does transactions that contain individual items stored in a separate table. I need the primary key txId to create the individual records that are linked with a Foreign Key.
Here is an excerpt from the entity:
public class Transactions implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "tx_id")
private Long txId;
//remainder left off for brevity
}
Here is an excerpt from the client:
public void create() {
persist(PersistAction.CREATE, "blah");
}
My major question is how can I get the Primary Key returned back from the persist() method?

Cannot find column [id] for OneToOne?

#Entity
#Table(name = "users")
public class User extends Model
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Long id;
#OneToOne(mappedBy= "user", cascade = {CascadeType.ALL})
#JoinColumn(name="info_id",referencedColumnName = "id")
public Info info;
}
#Entity
#Table(name="infos")
public class Info extends Model
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Long id;
#OneToOne(mappedBy="info",cascade = {CascadeType.ALL})
#JoinColumn(name="user_id", referencedColumnName = "id")
public User user;
}
And in my migration, users table includes a info_id column of bigint type, and infos table includes a user_id column of bigint type.
However, when i run the application, it gives me PersistenceException: Error with the Join on [models.Info.user]. Could not find the matching foreign key for [id] in table[users]? Perhaps using a #JoinColumn with the name/referencedColumnName attributes swapped?
Can anyone provide some insight into what's wrong in my code and how to fix it? Thank you.
Try this,
User Model
#OneToOne
#JoinColumn(name="info_id")
public Info info;
Info Model
#OneToOne
#JoinColumn(name="user_id")
public User user;
You shouldn't use mappedBy along with JoinColumn. See the difference here.