org.springframework.dao.DataIntegrityViolationException: POSTGRESQL - spring

Hi I am currently confused right now I have the following code:
Controller:
#GetMapping("/displayFile")
public List<Files> getFile(){
return dbFileRepository.findAll();
}
Model:
#Entity
public class Files implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
private String fileId;
private String fileName;
private String fileType;yy
#Lob
private byte[] fileData;
//setters and getters
this code works fine when I'm using MYSQL but when I migrated my MYSQL DB into POSTGRESQL then it suddenly did not work I am confused as to why this particular endpoint did not work on a simple select * query statement while my other endpoint that has similar select * query works here is the full stack trace thank you in advance
"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "could not execute query; SQL [select files0_.file_id as file_id1_2_, files0_.file_data as
file_dat2_2_, files0_.file_name as file_nam3_2_, files0_.file_type as file_typ4_2_ from files
files0_]; nested exception is org.hibernate.exception.DataException: could not execute query",

Related

I'm Trying to create table "User" in DB with using spring data JPA. How can I do that? [duplicate]

This question already has answers here:
Create user table name with hibernate
(2 answers)
Closed 22 days ago.
why can't I create table in db - "user" using spring data JPA ?
#Entity
#Data
#NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
#RequiredArgsConstructor
#Table(name = "user")
public class User implements UserDetails {
private static final long serialVersionUID = 1;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private final String username;
private final String password;
private final String fullName;
private final String street;
private final String city;
private final String state;
private final String zip;
private final String phoneNumber;
}
I get an error while initializing the program
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table user (id bigint not null, city varchar(255)...
I change Class name from "user" to "users" and the problem was solved but what is the reason of that error ?
user is a reserved word in SQL and Postgres. Many databases have reserved words, so you can run into collision sometimes.
Actually, JPA supports the following syntax for specifiyng the tablename (you can escape the table name)
#Table(name="\"user\"")
but it may cause problems in the future (in a query for example) and you should avoid using reserved words
So it is better to use users word instead

Problem Retrieving Nextval in JPA Application

I need have a need to return nextVal at various times in my application. I have an entity class like the following:
#Entity
#Table(name = "TBL_CACL")
public class Cacl {
#Id
#SequenceGenerator(name = "caclGenerator", sequenceName = "caclSeq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "calcGenerator")
#Column(name = "ID")
private Integer id;
// more stuff below....
, and I added the following in my repository interface:
#Repository
public interface CaclRepository extends JpaRepository<Cacl, Integer> {
#Query(value = "SELECT caclSeq.nextval FROM Cacl", nativeQuery = true)
Long getNextSeriesId();
However when I attempt to read it like this:
long nextval = caclRepository.getNextSeriesId() + 1;
, I get this exception:
(can't show entire stack trace)
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: relation "cacl" does not exist
Its puzzling to me that I am getting error "cacl does not exist" because this application has been up and working for some time. All that I have done is add the #SequenceGenerator, updated the #GeneratorValue to link to the #SequenceGenerator annotation, and create the new query. I would be grateful for any ideas as to what I am doing wrong. thanks
My answer is based on simplifying my approach some. Now I am simply using the default sequences supplied by postgress. So for instance now I have:
#Entity
#Table(name = "TBL_CACL")
public class Cacl {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Integer id;
#Column(name="NAME")
private String name;
// more stuff below...
, then in the repository (after querying postgress to get default sequences) I have:
#Query(value = "select last_value from tbl_cacl_id_seq", nativeQuery = true)
public Integer getCurrentVal();
And then:
int nextval = caclRepository.getCurrentVal();
works fine.
you could try removing the native query
#Query(value = "SELECT nextval('caclSeq')", nativeQuery =
true)
Long getNextSeriesId();

EntityManager persist multiple relationship

I have spring boot rest api, I have persisted 1 table successfully, but when I tried to persist object which has 2 another relations and I got error:
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState:
HY000
o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'id' doesn't have a default value
here is my entity and entity manger persistance:
#Entity
#Table(name="booking")
public class Booking {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#Column(name="description")
private String description;
#OneToMany(mappedBy="booking",cascade = CascadeType.ALL)
private List<CategoriesBooking> bookingInfos = new ArrayList<>();
#Entity
#Table(name="category_booking")
public class CategoriesBooking {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#Column(name = "name")
private String name;
#ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
#JoinColumn(name="booking_id")
private Booking booking;
#OneToMany(mappedBy="categoriesBooking",cascade = CascadeType.ALL)
private List<OptionsBooking> options = new ArrayList<>();
#Entity
#Table(name="options_booking")
public class OptionsBooking {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
#JoinColumn(name = "catebooking_id")
private CategoriesBooking categoriesBooking;
#Transactional
#Repository
public class Services{
#PersistenceContext
protected EntityManager entityManager;
public Services() {
}
public boolean add(Booking booking){
try {
entityManager.persist(booking);
return true;
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
return false;
}
}
data:
{description: 'test for persist',
bookingInfos:[{
name:'test1',
options:[{
name: 'test1-test1'
}]
}]
}
I update for use MySQL
GenerationType.AUTO chooses an ID generation strategy suitable for your database. What it actually picks depends on the database you are using. But judging from the error message it assumes the id column to be some kind of IDENTITY field which creates a unique value upon insertion.
And it seems your schema doesn't declare the id column in this way.
The obvious fix is to change that.
Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of SchemaUpdate.
If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with SchemaExport.

Self-Referencing record leading to "Direct self-reference leading to cycle" exception

I have self referencing class
#Entity
#Table(name = "contacts")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "contacts")
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password_smartlpc")
private String password;
#Column(name = "full_name")
private String fullName;
#ManyToOne
private Contacts companyContact;
}
But for my one database record
id full_name username password company_contact_id
5 JAK movies abc xyz 5
This record has company_contact_id as its self id.Which while retrieving goes into self-referencing cycle.
Enter: com.fps.web.rest.errors.ExceptionTranslator.processRuntimeException()
with argument[s] =
[org.springframework.http.converter.HttpMessageNotWritableException: Could not
write content: Direct self-reference leading to cycle (through reference
chain: java.util.UnmodifiableRandomAccessList[2]-
>com.fps.domain.Contacts["companyContact"]-
>com.fps.domain.Contacts["companyContact"]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference
leading to cycle (through reference chain:
java.util.UnmodifiableRandomAccessList[2]-
>com.fps.domain.Contacts["companyContact"]-
>com.fps.domain.Contacts["companyContact"])]
Work Around i have tried
(fetch = FetchType.LAZY) = gives same error as above.
#JsonIgnore : removes error but does not retrieves Company_Contact_id
#JsonManagedReference #JsonBackReference same as above.
Unfortunately i cannot change database or alter it.Since its legacy.Any more things i can try ??
Thanks
Try using DTOs in JHipster, you'll get more control over JSON serialization rather than simply exposing your entity especially when you are constrained by legacy database schema.

EntityNotFoundException in Hibernate Many To One mapping however data exist

I'm getting an error
Caused by: javax.persistence.EntityNotFoundException: Unable to find tn.entities.AgenceBnq with id 01
when I get AgenceBnq through Employee
Employee class:
#Table(name = "EMPLOYEE")
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.employeMat = ?1"),
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "EMPLOYEE_MAT", unique = true, nullable = false, length = 15)
private String employeeMat;
...
#ManyToOne
#JoinColumn(name = "AGENCE_COD")
private AgenceBnq agenceBnq;
}
#Entity
#Table(name="AGENCEBNQ")
public class AgenceBnq implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="AGENCE_COD", unique=true, nullable=false, length=10)
private String agenceCod;
...
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="agenceBnq")
private Set<Employee> employees;
}
I'm calling namedQuery Employee.findById in DAO to retrieve data and I have to get AgenceBnq from Employee but get this error while calling query.getResultList()
#NotFound( action = NotFoundAction.IGNORE) isn't useful for me because data exist in AGENCEBNQ table and I have to retrieve date through Employee.
Is this a bug in hibernate ? I'm using hibernate version 3.6.7.Final
Firstly, You dont need query for it, the EnityManger.find(Employee.class, YOUR_ID) will do the job.
Secondly dont use ? in your queries but names (e.employeMat = :id) as it is easier to debug and less error prones for complicated queries.
Finally, check your DB table if the AGENCE_COD column in Employee table really contains the valid ID for your entitity that crashes (and that it length matches the ID length of AgenceBnq). It should work, the typical reason why it doesnt will be that your Employe.AGENCE_COD has defualt value and when creatubg the new EMploye you add it only to the Agence but you did not set Agence in the Employ.

Resources