Unable to update table using hibernate spring mvc - java

My entity class is as follows
package com.ibs.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "InitialMedicalCheckUpG3")
public class InitialMedicalCheckUpEntity {
private int imcsId;
private String empId, status, updatedBy, remarks;
Date updatedOn;
#Column(name = "IMCS_ID")
public int getImcsId() {
return imcsId;
}
public void setImcsId(int imcsId) {
this.imcsId = imcsId;
}
#Id
#Column(name = "EMP_ID")
#GeneratedValue(generator = "increment", strategy = GenerationType.AUTO)
#GenericGenerator(name = "increment", strategy = "increment")
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
#Column(name = "STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name = "UPDATED_BY")
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Column(name = "REMARKS")
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON", insertable = false)
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
}
Data access object ->
package com.ibs.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ibs.entity.InitialMedicalCheckUpEntity;
#Repository
public class InitialMedicalCheckUpDaoImpl implements InitialMedicalCheckUpDao {
#Autowired
SessionFactory sessionFactory;
#Override
public List<InitialMedicalCheckUpEntity> getConfirmedList() {
// TODO Auto-generated method stub
return null;
}
#Override
public List<InitialMedicalCheckUpEntity> getNonConfirmedList() {
// TODO Auto-generated method stub
return null;
}
#Override
public void update(InitialMedicalCheckUpEntity e) {
// TODO Auto-generated method stub
System.out.println(e.getStatus());
sessionFactory.getCurrentSession().update(e);
}
}
Hibernate prepared the following query for my update statement->
Hibernate:
update InitialMedicalCheckUpG3 set IMCS_ID=?, REMARKS=?,STATUS=?,UPDATED_BY=?, UPDATED_ON=? where EMP_ID=?
So the table is not getting updated.
I use Dao from a service class->
package com.ibs.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ibs.dao.InitialMedicalCheckUpDao;
import com.ibs.entity.InitialMedicalCheckUpEntity;
#Service
public class InitialMedicalCheckUpServiceImpl implements
InitialMedicalCheckUpService {
#Autowired
InitialMedicalCheckUpDao dao;
#Override
public List<InitialMedicalCheckUpEntity> getConfirmedList() {
// TODO Auto-generated method stub
return null;
}
#Override
public List<InitialMedicalCheckUpEntity> getNonConfirmedList() {
// TODO Auto-generated method stub
return null;
}
#Override
#Transactional
public void update(InitialMedicalCheckUpEntity e) {
// TODO Auto-generated method stub
dao.update(e);
}
}

Every operation through hibernate needs to be associated with a transaction. You need to make sure that your update operation is a part of a transaction and this unit of work is committed. Make sure that you are associating this operation with a transaction and commit it.

Use the #Transactional annotation before the InitialMedicalCheckUpDaoImpl class, or before every method. Spring will then automatically add transactional characteristics for all methods within this class. This has the disadvantage when you would like to have transactions that can do more than one dao action.
A better design would be to have another class (a service) that calls the methods defined in the dao. This class can then be annotated with the #Transactional. This will result in better transaction definition because some transactions can then span more than one database operation, like insert then update.
EDIT
I just noticed that you have not overriden the equals and hashcode methods in your entity class. These are needed by hibernate to know if the entity is already in the database before updating, if the entity was detached from the session at some point or is used in a set. You can use the id field for this.
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null) {
return false;
}
if (!(o instanceof InitialMedicalCheckUpEntity)) {
return false;
}
return this.getEmpId()==o.getEmpId();
}
#Override
public int hashCode() {
return empId;
}
You may want to take a look at this Question

Related

Cant get spring boot hibernate rest api to return a one to many relationship

I have modelled a car park with building and floor models. There is a one to many relationship between building and floor. I have built a rest controllers to retrieve the data. I am attempting to retrive the data via a simple get request to api/v1/parkingbuildings/1/. The issue is that when retrieving a building i do not see a list of floors as per my relation mapping. Any insight into any mistakes i may be making would be appreciated. Below is the json that gets returned;
{"building_id":1,"building_name":"Labadiestad","postcode":"SA78BQ","max_floors":14,"owner_name":"Schaefer, Gutmann and Braun"}
I am expecting to see a collection of floors in the payload and i cannot fathom why, ive written other similar simpler solutions that do the same without issue, ive compared my prior solutions and see little difference that matters in my approach.
Here is my building model
package com.admiral.reslink.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity(name = "parking_buildings")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ParkingBuilding {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long building_id;
private String building_name;
private String postcode;
private int max_floors;
private String owner_name;
// ToDo sort the relationships
#OneToMany(mappedBy = "parkingBuilding")
#JsonIgnore
private List<ParkingFloor> parkingFloors;
public ParkingBuilding() {
}
public long getBuilding_id() {
return building_id;
}
public void setBuilding_id(long building_id) {
this.building_id = building_id;
}
public String getBuilding_name() {
return building_name;
}
public void setBuilding_name(String building_name) {
this.building_name = building_name;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public int getMax_floors() {
return max_floors;
}
public void setMax_floors(int max_floors) {
this.max_floors = max_floors;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public List<ParkingFloor> getParkingFloors() {
return parkingFloors;
}
public void setParkingFloors(List<ParkingFloor> parkingFloors) {
this.parkingFloors = parkingFloors;
}
}
And here is my floor model
package com.admiral.reslink.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "parking_floors")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ParkingFloor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long floor_id;
private int floor_number;
private int max_height_inches;
private boolean is_covered;
private boolean is_disabled_access;
// ToDo sort the relationships
#ManyToOne
#JoinColumn(name="building_id", nullable=false)
private ParkingBuilding parkingBuilding;
#OneToMany(mappedBy = "parkingFloor")
#JsonIgnore
private List<ParkingSpace> parkingSpace;
public ParkingFloor() {
}
public long getFloor_id() {
return floor_id;
}
public void setFloor_id(long floor_id) {
this.floor_id = floor_id;
}
public int getFloor_number() {
return floor_number;
}
public void setFloor_number(int floor_number) {
this.floor_number = floor_number;
}
public int getMax_height_inches() {
return max_height_inches;
}
public void setMax_height_inches(int max_height_inches) {
this.max_height_inches = max_height_inches;
}
public boolean isIs_covered() {
return is_covered;
}
public void setIs_covered(boolean is_covered) {
this.is_covered = is_covered;
}
public boolean isIs_disabled_access() {
return is_disabled_access;
}
public void setIs_disabled_access(boolean is_disabled_access) {
this.is_disabled_access = is_disabled_access;
}
public ParkingBuilding getParkingBuilding() {
return parkingBuilding;
}
public void setParkingBuilding(ParkingBuilding parkingBuilding) {
this.parkingBuilding = parkingBuilding;
}
public List<ParkingSpace> getParkingSpace() {
return parkingSpace;
}
public void setParkingSpace(List<ParkingSpace> parkingSpace) {
this.parkingSpace = parkingSpace;
}
}
Here is my building controller
package com.admiral.reslink.controllers;
import com.admiral.reslink.models.ParkingBuilding;
import com.admiral.reslink.models.ParkingFloor;
import com.admiral.reslink.repositories.ParkingBuildingRepository;
import com.admiral.reslink.repositories.ParkingFloorRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api/v1/parkingbuildings")
public class ParkingBuildingController {
#Autowired
private ParkingBuildingRepository parkingBuildingRepository;
#GetMapping
public List<ParkingBuilding> list() {return parkingBuildingRepository.findAll();}
#GetMapping
#RequestMapping("{id}")
public ParkingBuilding get(#PathVariable Long id) {return parkingBuildingRepository.getById(id);}
#PostMapping
public ParkingBuilding create(#RequestBody final ParkingBuilding parkingBuilding) {
return parkingBuildingRepository.saveAndFlush(parkingBuilding);
}
#RequestMapping(value="{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable Long id) {
parkingBuildingRepository.deleteById(id);
}
#RequestMapping(value="{id}", method = RequestMethod.PUT)
public ParkingBuilding update(#PathVariable Long id, #RequestBody ParkingBuilding parkingBuilding) {
ParkingBuilding existingParkingBuilding = parkingBuildingRepository.getById(id);
BeanUtils.copyProperties(parkingBuilding, existingParkingBuilding, "building_id");
return parkingBuildingRepository.saveAndFlush(existingParkingBuilding);
}
}
Not sure how you are retrieving the floors. OneToMany is by default lazy and would not load unless asked.
In your repository, try:
#EntityGraph(attributePaths = "parkingFloors")
ParkingBuilding findById(long id);

Spring Boot JPA not updating MySQL database after PUT request

I have made a spring boot application connected to an angular front end. When the user enters a value into attendance id and hits submit on the form, this calls a method that updates the current value in the database using a HTTP PUT request.
However, the value is not being update despite break points showing the new value is being received and updated.
I am new to spring boot so any help is appreciated.
package com.example.demo.Attendance;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.transaction.Transactional;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.LessonRun.LessonRun;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
public class Attendance {
#EmbeddedId
private AttendancePK id;
#ManyToOne
#JoinColumn(name="attendance_type", insertable = false, updatable=false)
private AttendanceType attendanceType;
#ManyToOne
#JsonIgnore
#JoinColumn(name="lesson_run_id", insertable = false, updatable=false)
private LessonRun lessonRun;
public LessonRun getLessonRun() {
return lessonRun;
}
public void setLessonRun(LessonRun lessonRun) {
this.lessonRun = lessonRun;
}
public AttendanceType getAttendanceType() {
return attendanceType;
}
public void setAttendanceType(AttendanceType attendanceType) {
this.attendanceType = attendanceType;
}
public Attendance(AttendancePK id, AttendanceType attendanceType, LessonRun lessonRun) {
super();
this.id = id;
this.attendanceType = attendanceType;
this.lessonRun = lessonRun;
}
public Attendance() {
}
public AttendancePK getId() {
return id;
}
public void setId(AttendancePK id) {
this.id = id;
}
}
My controller
#RequestMapping(value="/attendance/{attendanceId}/student/{studentId}/lessonrun/{lessonRunId}",method = RequestMethod.PUT)
public void updateAttendance(#PathVariable int attendanceId, #PathVariable int studentId, #PathVariable int lessonRunId, #RequestBody int attendanceTypeId) {
AttendancePK id = new AttendancePK(attendanceId, studentId,lessonRunId);
Attendance attendanceInDB = attendanceService.getAttendancebyId(id);
// attendanceInDB.setAttendanceType(int.getAttendanceType());
attendanceService.updateAttendance(attendanceInDB, attendanceTypeId);
}
My Service
package com.example.demo.Attendance;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.AttendanceType.AttendanceTypeRepository;
#Service
public class AttendanceService {
#Autowired
private AttendanceRepository attendanceRepository;
#Autowired
private AttendanceTypeRepository attendanceTypeRepository;
public List<Attendance> getAllAttendanceRecs() {
List<Attendance> attendanceList = new ArrayList<>();
attendanceRepository.findAll().forEach(attendanceList::add);
return attendanceList;
}
public Attendance getAttendancebyId(AttendancePK id) {
Optional<Attendance> optionalAttendance = attendanceRepository.findById(id);
if (optionalAttendance.isPresent()) {
return optionalAttendance.get();
}
return null;
}
public void updateAttendance(Attendance attendanceInDB, int attendanceTypeId) {
Optional<AttendanceType> attendanceType = attendanceTypeRepository.findById(attendanceTypeId);
if (attendanceType.isPresent()) {
attendanceInDB.setAttendanceType(attendanceType.get());
attendanceRepository.save(attendanceInDB);
}
}
}
the breakpoint results show the value is updated shown here
but MySQL database doesn't reflect this

Crud implementation in Eclipse, JSF, Java

I have a class (Vehicles) and I implemented CRUD operations. Delete works, update works, just create doesn't work.
What can I put instead of this create code?
P.S.: I use Eclipse
AND THIS IS FormMasini.java where I take from Vehicule.java dates and it will show in a JSF Form. The error appears at this line: this.vehicul = new Vehicul();
package vehiculeFeaa;
import java.util.List;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
#Entity
#Table(name = "VEHICUL")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "VEHICUL_TYPE")
public abstract class Vehicul {
#TableGenerator(name = "VEHICUL_GEN", table = "ID_GEN", pkColumnName = "GEN_NUME", valueColumnName = "GEN_VALOARE", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "VEHICUL_GEN")
private int idVehicul;
private String producator;
public int getIdVehicul() {
return idVehicul;
}
public void setIdVehicul(int idVehicul) {
this.idVehicul = idVehicul;
}
public String getProducator() {
return producator;
}
public void setProducator(String producator) {
this.producator = producator;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public List<Vehicul> get(int i) {
// TODO Auto-generated method stub
return null;
}
}
package masinifeaa;
import java.util.ArrayList;
import java.util.List;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import vehiculeFeaa.Vehicul;
public class FormMasini {
private Vehicul vehicul;
private List<Vehicul>vehicule=new ArrayList<Vehicul>();
public Vehicul getVehicul() {
return vehicul;
}
public void setVehicul(Vehicul vehicul) {
this.vehicul = vehicul;
}
public List<Vehicul> getVehicule() {
return vehicule;
}
public void setVehicule(List<Vehicul> vehicule) {
this.vehicule = vehicule;
}
private EntityManager em;
#SuppressWarnings("unchecked")
public FormMasini() {
EntityManagerFactory emf=
Persistence.createEntityManagerFactory("FirmeJPA");
em=emf.createEntityManager();
this.vehicule= em.createQuery("SELECT v FROM Vehicul v")
.getResultList();
if(!this.vehicule.isEmpty())
vehicul=this.vehicule.get(0);
}
public void backVehicul(ActionEvent evt) {
Integer idxCurent = this.vehicule.indexOf(vehicul);
if(idxCurent > 0)
this.vehicul=this.vehicule.get(idxCurent-1);
}
public void nextVehicul(ActionEvent evt) {
Integer idxCurent = this.vehicule.indexOf(vehicul);
if((idxCurent + 1) < this.vehicule.size())
this.vehicul=this.vehicule.get(idxCurent + 1);
}
//Implementez actiunile CRUD
public void deleteVehicul(ActionEvent evt) {
this.vehicule.remove(this.vehicul);
if(this.em.contains(this.vehicul)) {
this.em.getTransaction().begin();
this.em.remove(this.vehicul);
this.em.getTransaction().commit();
}
if(!this.vehicule.isEmpty())
this.vehicul=this.vehicule.get(0);
else
this.vehicul=null;
}
public void saveVehicul(ActionEvent evt) {
this.em.getTransaction().begin();
this.em.persist(this.vehicul);
this.em.getTransaction().commit();
}
public void abandonVehicul(ActionEvent evt) {
if(this.em.contains(this.vehicul))
this.em.refresh(this.vehicul);
}
public void createVehicul(ActionEvent evt) {
this.vehicul = new Vehicul();
this.vehicul.setidVehicul(999);
this.vehicul.setNume("New car");
this.vehicule.add(this.vehicul);
}
Nothing related to JSF or something else. You just can't instantiate a abstract class, thats basic java.

hibernate two way mapping insert and delete beginner

Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.
I explicitly want to have this two way mappings.
Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.
Everything works fine, if I do a session.close and open a new session for deleting the user.
I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.
public class Worker implements Iworker{
private Sessiongetter sg;
private MainMenu mm;
public void work(File datei)
{
sg = new Sessiongetter();
Session session = sg.getSesseion();
WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");
Buch buch = new Buch("test", "ich", 1);
buch.setWlBuchart(wlBuchart);
Buch buch2 = new Buch("versuch", "du",2);
buch2.setWlBuchart(wlBuchart);
session.beginTransaction();
session.save(wlBuchart);
session.save(buch);
session.save(buch2);
Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
session.save(benutzer);
Leihstellung leihstellung = new Leihstellung(benutzer, buch);
Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
session.save(leihstellung);
session.save(leihstellung2);
benutzer.addLeihstellung(leihstellung);
benutzer.addLeihstellung(leihstellung2);
session.update(benutzer);
buch.addLeihstellung(leihstellung);
buch2.addLeihstellung(leihstellung2);
session.update(buch);
session.update(buch2);
session.remove(benutzer);
session.flush();
session.getTransaction().commit();
session.close();
System.out.println("fertig");
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.Session;
#Entity
#Table(name="benutzer")
public class Benutzer {
#Column(nullable=false)
private String vorname, nachname, gruppe;
#Id
private String kennung;
private boolean admin;
#Column(nullable=true)
private String kennwort;
#OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
private List<Leihstellung>leihstellungs;
public String getKennwort() {
return kennwort;
}
public void setKennwort(String kennwort) {
this.kennwort = kennwort;
}
public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
this.vorname=vorname;
this.nachname=nachname;
this.gruppe=gruppe;
this.kennung=kennung;
this.leihstellungs= new ArrayList<>();
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
public String getVorname() {
return vorname;
}
public String getNachname() {
return nachname;
}
public String getGruppe() {
return gruppe;
}
public String getKennung() {
return kennung;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
public int compare(Benutzer other)
{
if (this.getNachname().compareTo(other.getNachname())!=0)
{
return this.getNachname().compareTo(other.getNachname());
}
return this.getVorname().compareTo(other.getVorname());
}
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.ManyToAny;
#Entity
#Table(name="buch")
public class Buch {
#Column(nullable=false)
private String titel;
private String autor;
#ManyToOne
private WlBuchart wlBuchart;
#OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
private List<Leihstellung>leihstellungs;
public WlBuchart getWlBuchart() {
return wlBuchart;
}
public void setWlBuchart(WlBuchart wlBuchart) {
this.wlBuchart = wlBuchart;
}
#Id
private int nummer;
public Buch(String titel, String autor,int nummer) {
this.titel=titel;
this.autor=autor;
this.nummer=nummer;
leihstellungs = new ArrayList<>();
}
public Buch() {
// TODO Auto-generated constructor stub
}
public String getTitel() {
return titel;
}
public String getAutor() {
return autor;
}
public int getNummer() {
return nummer;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
}
package code.logik;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="leihstellung")
public class Leihstellung {
#ManyToOne
private Benutzer benutzer;
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private LocalDate von;
private LocalDate bis;
#ManyToOne
private Buch buch;
public Leihstellung(Benutzer benutzer, Buch buch) {
this.benutzer=benutzer;
this.buch=buch;
this.von = LocalDate.now();
}
public Leihstellung() {
// TODO Auto-generated constructor stub
}
public void setAbgegeben()
{
bis = LocalDate.now();
}
public Benutzer getBenutzer() {
return benutzer;
}
public int getId() {
return id;
}
public LocalDate getVon() {
return von;
}
public LocalDate getBis() {
return bis;
}
public Buch getBuch() {
return buch;
}
}
Found the solution myself. I had to delete the references from the connected rents and books.
Now everything works find.

Updating primary key spring boot jpa

i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help!
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Altering the PK of an entity is not permitted - if you really have to do it, you should delete, and recreate it.
Reference (an older question) : JPA Hibernate - changing the primary key of an persisted object

Categories

Resources