Method threw 'org.springframework.dao.DataIntegrityViolationException' exception - java

I have this entity
#Entity
#Table(name = "REPORT_TASCK")
#Data
public class ReportTasck {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public Long id;
#Column(name = "type")
public String type;
#Column(name = "status")
public Integer status;
#Column(name = "type")
#OneToMany(mappedBy = "reportTasck", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Bill> bills;
}
and
#Entity
#Table(name = "BIIL")
#Data
public class Bill {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public Long id;
#Column(name = "neme")
public String neme;
#Column(name = "status")
public Integer status;
#ManyToOne()
#JoinColumn(name = "REPORT_TASCK_ID")
public ReportTasck reportTasck;
}
then I tried fill it and save
ReportTasck reportTasck = new ReportTasck();
reportTasck.setStatus(0);
reportTasck.setType("standart");
List<Bill> bills = new ArrayList<>();
for (BillDto billDto : all) {//640 items
Bill bill = new Bill();
bill.setStatus(0);
bill.setNeme(billDto.getBill());
bill.setReportTasck(reportTasck);
bills.add(bill);
}
reportTasck.setBills(bills);
reportTasckRepository.save(reportTasck);
but when start this line reportTasck.setBills(bills); I get error in debbug mode Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate entity.ReportTasck.toString()
and when I tried save I get this error Method threw 'org.springframework.dao.DataIntegrityViolationException' exception.
could not execute statement; SQL [n/a]; constraint [null]
I dont understand why I get this error and how fix

Related

How to find a list of an object by a nested table?

Such a problem. I have an entity. I need to get a list of objects of this entity by selection, namely by the body_material field. That is, for example, find all BoatCards whose body_material index is 2. I do this in Java using Spring. I have added Dao, Service, Controller and entity's classes
BoatBodyMaterial entity:
#Entity
#Table(name = "boat_body_material")
#Data
#NoArgsConstructor
public class BoatBodyMaterial {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "matcode")
private Integer matcode;
#Column(name = "matname")
private String matname;
#Column(name = "matnote")
private String matnote;
}
BoatCards entity:
#Entity
#Table(name = "boat_cards")
#Data
#NoArgsConstructor
#FieldDefaults(level = AccessLevel.PRIVATE)
public class BoatCards {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cardid")
Long cardid;
#Column(name = "reg_num")
String regNum;
#Column(name = "tiket_num")
String tiketNum;
#Column(name = "boat_name")
String boatName;
#ManyToOne
#JoinColumn(name = "boat_type")
BoatTypes boatType;
#Column(name = "boat_year")
String boatYear;
#Column(name = "boat_vin")
String boatVin;
#Column(name = "parking_place")
String parkingPlace;
#ManyToOne
#JoinColumn(name = "sa_category")
SaCategory saCategory;
#Column(name = "boat_length")
String boatLength;
#Column(name = "boat_width")
String boatWidth;
#Column(name = "boat_height")
String boatHeight;
#ManyToOne
#JoinColumn(name = "body_material")
BoatBodyMaterial bodyMaterial;
#Column(name = "boat_payload")
Long boatPayload;
#Column(name = "passengers_num")
Long passengersNum;
#Column(name = "service_life")
String serviceLife;
#Column(name = "engine_num")
Long engineNum;
#ManyToOne
#JoinColumn(name = "owner")
PersonData owner;
#ManyToOne
#JoinColumn(name = "agent")
PersonData agent;
#Column(name = "note")
String note;
}
Dao class:
public interface BoatCardsDao extends JpaRepository<BoatCards, Integer> {
#Query(value = "SELECT * from gims.boat_body_material where matcode = 1", nativeQuery = true)
BoatBodyMaterial findByBodyMaterial ();
List<BoatCards> findAllByBodyMaterial(BoatBodyMaterial list);
}
Service class:
public List<BoatCards> getAllByMaterial() {
BoatBodyMaterial matcodeFromTable = boatCardsDao.findByBodyMaterial();
List<BoatCards> boatCards = boatCardsDao.findAllByBodyMaterial(matcodeFromTable);
return boatCards;
}
Controller class:
#GetMapping(path="/get")
public List<BoatCards> get() {
return boatCardsService.getAllByMaterial();
}
I get ERROR:
2023-01-26T10:33:20.193+03:00 ERROR 20852 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [by.compit.gimsshd.model.BoatBodyMaterial] for value '{1, metal, produce from metal}'] with root cause
I resolve this problem! Thank you!
public interface BoatCardsDao extends JpaRepository<BoatCards, Integer> {
List<BoatCards> findAllByBodyMaterialMatcode(Integer bodyMaterial);
}
Try something like this:
public interface BoatCardsDao extends JpaRepository<BoatCards, Integer> {
#Query(value = "SELECT card FROM BoatCards card"
+ " JOIN card.bodyMaterial mat"
+ " WHERE mat.matcode = :matcode")
List<BoatCards> findAllByBodyMaterial(#Param("matcode") int matcode);
}

I have Mapping Exception on my Spring Boot project

I have a 3 models and 1 table to Many to many relationship on my project
this:
#Embeddable
#Getter
#Setter
public class ProductWarehouseId implements Serializable {
#Column(name = "warehouse_Id")
private Long warehouseId;
#Column(name = "product_Id")
private Long productId;
#Column(name = "user_Id")
private Long userId;
public ProductWarehouseId() {
}
public ProductWarehouseId(Long warehouseId, Long productId, Long userId) {
this.warehouseId = warehouseId;
this.productId = productId;
this.userId = userId;
}
}
---------------------------------------------------
#Entity
#NoArgsConstructor
#Getter
#Setter
public class ProductWarehouse {
#EmbeddedId
ProductWarehouseId productWarehouseId;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("productId")
#JoinColumn(name = "product_id")
ProductEntity product ;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("warehouseId")
#JoinColumn(name = "warehouse_id")
WarehouseEntity warehouse ;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
#JoinColumn(name = "user_id")
UserEntity userEntity;
#Column(name = "stockAmount")
private Long stockAmount;
#Column(name = "transctionDate")
#Temporal(TemporalType.TIMESTAMP)
private Date transactionDate = new Date();
public ProductWarehouse(ProductEntity product, UserEntity user) {
this.product = product;
this.userEntity = user;
}
}
********************************************************
#Getter
#Setter
#Entity
#RequiredArgsConstructor
public class ProductEntity extends BaseEntity{
#OneToMany(mappedBy = "product",cascade = CascadeType.ALL)
private Set<ProductWarehouse> productWarehouses;
//And more veriables
}
------------------------------------
#Getter
#Setter
#Entity
public class WarehouseEntity extends BaseEntity{
#OneToMany(mappedBy = "warehouse",cascade = CascadeType.ALL)
private Set<ProductWarehouse> productWarehouses = new HashSet<>();
//and more veriables
}
When i trying to select list from product_warehouse table to make changes, i have some Exceptions.
I want to transfer the products between warehouses using fromId and toId
I using this method in service class:
#Override
#Transactional
public void transfer(Long fromId, Long toId) {
WarehouseEntity warehouseEntity = warehouseCRUDRepository.getOne(fromId);
WarehouseEntity warehouseEntity1 = warehouseCRUDRepository.getOne(toId);
if (warehouseEntity.getStatus().equals(WarehouseStatus.ACTIVE) && warehouseEntity1.getStatus().equals(WarehouseStatus.ACTIVE)){
Collection<ProductWarehouse> productWarehouses = em
.createNativeQuery("select c from product_warehouse c where c.warehouse_id =:fromId")
.setParameter("fromId",fromId)
.getResultList();
for (ProductWarehouse p : productWarehouses){
p.getProductWarehouseId().setWarehouseId(toId);
p.setWarehouse(warehouseCRUDRepository.getOne(toId));
}
}
}
And the Exception is :
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2002] with root cause.
Can you hep me please.
I am sorry for my English, and thank you.
ProductWarehouse is already having Warehouse in it, I don't understand why are you again setting it up by fetching it from DB inside the for loop.
I don't see any necessity of the for loop in that method, also as you described above you haven't defined many to many relationship anywhere. while building the relationship you can use the join table as explained here
if you need more information, please share more details of your need and errors you are facing.

Foreign key is null : Hibernate Spring

I try to save object Run to database. I defined relation between Run and City. One city could have many runs. I got problem with city_id. Is null.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'city_id' cannot be null
My entieties and controller:
City
#Entity
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "cities")
public class City {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "city_id")
private long id;
#OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Run> runs = new ArrayList<>();
private String name;
}
Run
#Entity
#Builder
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "runs")
public class Run {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name_run")
private String nameRun;
#Column(name = "distance")
private double distance;
#Column(name = "date")
private Date date;
#Column(name = "my_time")
private String myTime;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "city_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private City city;
}
Controller
#CrossOrigin
#RestController
#RequestMapping("/api/")
public class RunController {
private RunRepository runRepository;
private RunService runService;
public RunController(RunRepository runRepository, RunService runService) {
this.runRepository = runRepository;
this.runService = runService;
}
#GetMapping("runs")
public ResponseEntity<List<Run>> getRuns() {
return runService.getRuns();
}
#PostMapping("runs")
public ResponseEntity addRun(#RequestBody Run run) {
return new ResponseEntity<>(runRepository.save(run), HttpStatus.OK);
}
}
I would like to save the run in DB.
My test request looks like :
{
"nameRun": "test",
"distance":"5.0",
"date":"2020-12-12",
"myTime":"50:40",
"city":"test1"
}
Result from evaluate expresion in Intelijj:
Why the City = null? Is here error in mapping?
Can you try with this json but you need to pass city id in json.
{
"nameRun": "test",
"distance": "5.0",
"date": "2020-12-12",
"myTime": "50:40",
"city": {
"id": 1,
"name": "test1"
}
}
Thanks
First of all, use Long for id please. It is better to add #Entity annotation too.
#Entity
public class City {
#Id
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Run> runs = new ArrayList<>();
}
#Entity
public class Run {
#Id
#GeneratedValue
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private City city;
}
You need to set city_id when you save Run.
The simplest way to do that is just create a fake transient City and set id to it.
City city = new City();
city.setId(1L);
Run run = new Run();
run.setCity(city);
repository.save(run);
Obviously you should have a city with id 1L in the database.
Other options are
Use something like session.load() Hibernate analogue with Spring repository to create City without loading it from datatbase.
Load City entity entirely by id.
if you wanna save any run class,
Run run = new Run();
City city = new City();
city.getRuns().add(run);
runRepository.save(run);
if you wanna save any run class, first you need to insert to (Arraylist) runs variable of city class like city.getRuns().add(run) after filling run then you can runRepository.save(run).
Also my samples are here. You can look at myclasses.
First class is called Patient .
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#ToString
#Table(name = "aapatient")
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
#SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
#Column(name = "patientid")
private Long patientid;
private String name;
private String lastname;
#OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Problem> problems;
}
Second Class called Problem is this one.
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Entity
#Table(name="aaproblem")
public class Problem{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
#SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
#Column(name = "problemid")
private Long problemid;
private String problemName;
private String problemDetail;
#Temporal(TemporalType.TIMESTAMP)
Date creationDate;
#NotNull
#ManyToOne(optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id")
private Patient patient;
}

Hibernate query on embeddable

here's the problem:
I want to withdraw a list of UserDomains from database with a method:
#Query("SELECT dom FROM User usr JOIN usr.domains dom")
List<UserDomain> findDomains();
here is my entity and embeddable class:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "usr_id")
private Integer id;
#Column(name = "usr_username")
private String username;
#Column(name = "usr_password")
private String password;
#Column(name = "usr_email")
private String email;
#ElementCollection
#JoinTable(name = "user_domains", joinColumns = #JoinColumn(name = "udo_usr_id"))
private Set<UserDomain> domains;
#Embeddable
public class UserDomain {
#Column(name = "udo_dom_guid")
private String domGuid;
#Column(name = "udo_company_guid")
private String companyGuid;
the problem is when I'm trying to execute the query within GET method I'm getting an error:
"could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
I've been trying to solve this for many hours :( thanks in advance

StackOverflow Exception while using Hibernate and Jackson on bi-directional objects

I am trying some hibernate.The following is the pojo I am using,
#Entity
#Table(name = "person")
public class Person {
#Id
#GeneratedValue
#Column(name = "person_id")
private long person_id;
#Column(name = "name")
private String name;
#Column(name = "Address")
private String Address;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "person" )
private Set<Phone> phone;
//Getters ande Setters
}
#Entity
#Table(name = "phone")
public class Phone{
#Id
#GeneratedValue
#Column(name = "phone_id")
private long phone_id;
#Column(name = "name")
private String name;
#ManyToOne(cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinColumn(name = "person_id")
private Person person ;
//Getters ande Setters
}
What I want is when I fetch a record from person and need corresponding all phone details. (Like Select * from person) I have around 1360 data in person and nearly double in phone. But for some reason error is thrown. I am not able to see full error stack . Below is the error I am getting.
at
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:117)
~[jackson-databind-2.4.6.jar:2.4.6] at
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
~[jackson-databind-2.4.6.jar:2.4.6] at
.....
I was not able to post all error that I got
Using JsonManagedReference and JsonBackReference annotations may solve your problem.
While jackson trying to convert objects to json, visits objects and
their attributes. So if objects have bi-directional relations, for
jackson we need to think about cyclic dependencies. Jackson starts
serialize person and see the phone list and take a phone from list and
start serialize phone and sees person in phone and take person from
phone and start serilize it bla bla bla so this is an endless loop. If
jackson sees these annotations, stops and breaks the loop.
Give it a try as below code;
#Entity
#Table(name = "person")
public class Person {
#Id
#GeneratedValue
#Column(name = "person_id")
private long person_id;
#Column(name = "name")
private String name;
#Column(name = "Address")
private String Address;
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "person" )
private Set<Phone> phone;
// Getters and Setters
}
#Entity
#Table(name = "phone")
public class Phone{
#Id
#GeneratedValue
#Column(name = "phone_id")
private long phone_id;
#Column(name = "name")
private String name;
#ManyToOne(cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinColumn(name = "person_id")
#JsonBackReference
private Person person;
// Getters and Setters
}
You can alternatively use #JsonIdentityInfo on classes
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#id")
#Table(name = "phone")
public class Phone {
}
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#id")
#Table(name = "person")
public class Person {
}
I was also getting the same error.
Using #JsonBackReference and #JsonManagedReference was still giving me error so I used #JsonIdentityInfo and it worked like a charm.
Below are my classes :-
BookModel :
#Data
#Entity
#Table(name = "book")
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="bookId")
public class BookModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "book_id")
private int bookId;
#Column(name="book_name")
private String bookName;
#Column(name="book_author")
private String bookAuthor;
#Column(name="book_publish_date")
private Date bookPublishDate;
#Column(name="book_price")
private double bookPrice;
#OneToMany(mappedBy = "book_model")
List<BookImagesModel> bookImagesModels;
//getters and setters
//default constructor
}
BookImagesModel :
#Data
#Entity
#Table(name = "book_images")
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="imageId")
public class BookImagesModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "image_id")
private long imageId;
#ManyToOne
#JoinColumn(name = "book_id")
private BookModel book_model;
#Column(name = "image_path")
private String imagePath;
//getters and setters
//default constructor
}
I used Mysql8 database with spring boot.

Categories