Delete a record using Spring data jpa - rest

I have an entity 'Competence', this entity has OneToMany relation with two other entities : CandidatCompetence and OffreCompetence, and a ManyToOne relation with GroupCompetence.
And I have a rest delete service with will take the id of a Competence entity as following :
#Secured("ROLE_ADMIN")
#RequestMapping(value="/competences/{id}",method= RequestMethod.DELETE)
public void deleteCompetence(#PathVariable Long id) {
competenceMetier.deleteCompetence(id);
}
Then the deleteCompetence function will call a delete function from the Competence Repository which extends JpaRepository<Competence, Long> as following :
public void deleteCompetence(Long id) {
competenceRepository.delete(id);
}
The problem is that when I call the rest delete method, I get 200 as an http response, but nothing in the body, the same for the log I can't see the DELETE sql query anywhere, and the entity still exists in the database.
here are my entities :
Competence :
#Entity
public class Competence implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long codeCompetence;
private String titre;
private Boolean activated = true;
#OneToMany(mappedBy="competence",cascade = CascadeType.ALL)
private Collection<CandidatCompetence> candidatCompetences;
#OneToMany(mappedBy="competence",cascade = CascadeType.ALL)
private Collection<OffreCompetence> offreCompetences;
#ManyToOne
#JoinColumn(name = "groupCompetence")
private GroupCompetence groupCompetence;
public Long getCodeCompetence() {
return codeCompetence;
}
public void setCodeCompetence(Long codeCompetence) {
this.codeCompetence = codeCompetence;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
#JsonIgnore
#XmlTransient
public Collection<CandidatCompetence> getCandidatCompetences() {
return candidatCompetences;
}
#JsonSetter
public void setCandidatCompetences(Collection<CandidatCompetence> candidatCompetences) {
this.candidatCompetences = candidatCompetences;
}
#JsonIgnore
#XmlTransient
public Collection<OffreCompetence> getOffreCompetences() {
return offreCompetences;
}
public void setOffreCompetences(Collection<OffreCompetence> offreCompetences) {
this.offreCompetences = offreCompetences;
}
public Competence(String titre) {
super();
this.titre = titre;
}
public Competence() {
super();
// TODO Auto-generated constructor stub
}
#JsonIgnore
#XmlTransient
public GroupCompetence getGroupCompetence() {
return groupCompetence;
}
#JsonSetter
public void setGroupCompetence(GroupCompetence groupCompetence) {
this.groupCompetence = groupCompetence;
}
public Boolean getActivated() {
return activated;
}
public void setActivated(Boolean activated) {
this.activated = activated;
}
}
OffreCompetence :
#Entity
public class OffreCompetence implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long codeOffreCompetence;
private String niveauRequis;
#ManyToOne
#JoinColumn(name = "competence")
private Competence competence;
#ManyToOne
#JoinColumn(name="offre")
private Offre offre;
public Long getCodeOffreCompetence() {
return codeOffreCompetence;
}
public void setCodeOffreCompetence(Long codeOffreCompetence) {
this.codeOffreCompetence = codeOffreCompetence;
}
public String getNiveauRequis() {
return niveauRequis;
}
public void setNiveauRequis(String niveauRequis) {
this.niveauRequis = niveauRequis;
}
public Competence getCompetence() {
return competence;
}
public void setCompetence(Competence competence) {
this.competence = competence;
}
#JsonIgnore
public Offre getOffre() {
return offre;
}
#JsonSetter
public void setOffre(Offre offre) {
this.offre = offre;
}
public OffreCompetence(String niveauRequis) {
super();
this.niveauRequis = niveauRequis;
}
public OffreCompetence() {
super();
// TODO Auto-generated constructor stub
}
}
CandidatCompetence :
#Entity
public class CandidatCompetence implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long codeCandidatCompetence;
private String niveauExperience;
#ManyToOne
#JoinColumn(name = "candidat")
private Candidat candidat;
#ManyToOne
#JoinColumn(name = "competence")
private Competence competence;
public Long getCodeCandidatCompetence() {
return codeCandidatCompetence;
}
public void setCodeCandidatCompetence(Long codeCandidatCompetence) {
this.codeCandidatCompetence = codeCandidatCompetence;
}
public String getNiveauExperience() {
return niveauExperience;
}
public void setNiveauExperience(String niveauExperience) {
this.niveauExperience = niveauExperience;
}
public Candidat getCandidat() {
return candidat;
}
public void setCandidat(Candidat candidat) {
this.candidat = candidat;
}
public Competence getCompetence() {
return competence;
}
public void setCompetence(Competence competence) {
this.competence = competence;
}
public CandidatCompetence(String niveauExperience) {
super();
this.niveauExperience = niveauExperience;
}
public CandidatCompetence() {
super();
// TODO Auto-generated constructor stub
}
}
GroupCompetence :
#Entity
public class GroupCompetence implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long codeGroupCompetence;
private String titre;
private Boolean activated = true;
#OneToMany(mappedBy="groupCompetence",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Collection<Competence> competences;
public Long getCodeGroupCompetence() {
return codeGroupCompetence;
}
public void setCodeGroupCompetence(Long codeGroupCompetence) {
this.codeGroupCompetence = codeGroupCompetence;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public GroupCompetence(String titre) {
this.titre = titre;
}
public GroupCompetence() {
}
public Boolean getActivated() {
return activated;
}
public void setActivated(Boolean activated) {
this.activated = activated;
}
public Collection<Competence> getCompetences() {
return competences;
}
public void setCompetences(Collection<Competence> competences) {
this.competences = competences;
}
}

You should annotate your Service Method deleteCompetence with #Transactional.

Related

List not being saved

I'm trying to save a list of question options but its not being saved. Only the last row is being save.
Below is the code.
#Transactional
public void addQuestionOptions(QuestionOptionsRequest questionOptionsRequest, int questionId) {
List<QuestionOption> optionList = new ArrayList<>();
QuestionOption options = new QuestionOption();
Question question = questionRepository.findByQuestionId(questionId);
if(question != null) {
questionOptionsRequest.getQuestionOptions()
.stream()
.forEach(option -> {
options.setQuestionOption(option.getQuestionOption());
options.setQuestion(question);
options.setQuestionOptionNumber(option.getQuestionOptionNumber());
optionList.add(options);
});
questionOptionRepository.saveAll(optionList);
}
}
QuestionOption
#Entity
#JsonIgnoreProperties({"question"})
public class QuestionOption {
#Id
#GeneratedValue
private int questionOptionId;
private int questionOptionNumber;
private String questionOption;
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private Question question;
public void setQuestionOptionNumber(int questionOptionNumber)
{
this.questionOptionNumber = questionOptionNumber;
}
public void setQuestionOption(String questionOption)
{
this.questionOption = questionOption;
}
public String getQuestionOption()
{
return this.questionOption;
}
public int getQuestionOptionNumber()
{
return this.questionOptionNumber;
}
public int getQuestionOptionId() {
return questionOptionId;
}
public void setQuestionOptionId(int questionOptionId) {
this.questionOptionId = questionOptionId;
}
}
Question
#Entity
#Getter
#Setter
public class Question {
#Id
#GeneratedValue
private int questionId;
private int assessmentId;
private QuestionTypes questionType;
private String questionText;
private String questionURL;
private QuestionStatus questionStatus;
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="question")
private List<QuestionOption> questionOptions;
public void setQuestionId(int queId)
{
this.questionId = queId;
}
public void setQuestionText(String queTxt)
{
this.questionText = queTxt;
}
public void setQuestionType(QuestionTypes queType)
{
this.questionType = queType;
}
public void setQuestionURL(String queURL)
{
this.questionURL = queURL;
}
public int getQuestionId() {
return questionId;
}
public String getQuestionText() {
return questionText;
}
public QuestionStatus getQuestionStatus() {
return questionStatus;
}
public void setQuestionStatus(QuestionStatus questionStatus) {
this.questionStatus = questionStatus;
}
public QuestionTypes getQuestionTypes() {
return this.questionType;
}
public String getQuestionURL() {
return this.questionURL;
}
public int getAssessmentId() {
return this.assessmentId;
}
public void setAssessmentId(int assessmentId) {
this.assessmentId = assessmentId;
}
public QuestionTypes getQuestionType() {
return questionType;
}
}
You are creating only one object of QuestionOption
QuestionOption options = new QuestionOption();
Create this object inside for each.

Spring Boot JPA Bulk insert

I have 3 Entities Parent,Child,SubChild. Parent is a parent of Child and Child is a parent of SubChild. I need to insert around 700 objects of Parent. Parent can have 50 Objects of Child. Child can have 50 objects of SubChild.
I tried normal repository.save(ListOfObjects) it takes approx 4mins.
Then I tried using entity manager's persist, flush and clear based on batch size(500). This also took approx 4 mins.
There wasn't much difference in performance. Please suggest a best way to insert such a high amount of data efficiently.
Parent
#Entity
public class Parent {
#Id #GeneratedValue(strategy= GenerationType.AUTO)
private Long parentId;
private String aaa;
private String bbb;
private String ccc;
#Version
private Long version;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent", fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(column=#JoinColumn(name="parentId",referencedColumnName="parentId",nullable=false))})
private List<Child> childs = new ArrayList<>();
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public String getBbb() {
return bbb;
}
public void setBbb(String bbb) {
this.bbb = bbb;
}
public String getCcc() {
return ccc;
}
public void setCcc(String ccc) {
this.ccc = ccc;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public List<Child> getChilds() {
return childs;
}
public void setChilds(List<Child> childs) {
this.childs = childs;
}
}
Child
#Entity
public class Child {
#Id #GeneratedValue(strategy= GenerationType.AUTO)
private Long childId;
private String ddd;
private String ccc;
private Integer eee;
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = true, mappedBy = "child", fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(column = #JoinColumn(name = "childId", referencedColumnName = "childId", nullable = false)) })
private List<SubChild> subChilds = new ArrayList<>();
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(column= #JoinColumn( name="parentId",referencedColumnName="parentId",nullable=false))
})
private Parent parent;
public Long getChildId() {
return childId;
}
public void setChildId(Long childId) {
this.childId = childId;
}
public String getDdd() {
return ddd;
}
public void setDdd(String ddd) {
this.ddd = ddd;
}
public String getCcc() {
return ccc;
}
public void setCcc(String ccc) {
this.ccc = ccc;
}
public Integer getEee() {
return eee;
}
public void setEee(Integer eee) {
this.eee = eee;
}
public List<SubChild> getSubChilds() {
return subChilds;
}
public void setSubChilds(List<SubChild> subChilds) {
this.subChilds = subChilds;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
SubChild
#Entity
public class SubChild {
#Id #GeneratedValue(strategy= GenerationType.AUTO)
private Long subChildId;
private String fff;
private String ggg;
private Integer hhh;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(column= #JoinColumn( name="childId",referencedColumnName="childId",nullable=false))
})
private Child child;
public Long getSubChildId() {
return subChildId;
}
public void setSubChildId(Long subChildId) {
this.subChildId = subChildId;
}
public String getFff() {
return fff;
}
public void setFff(String fff) {
this.fff = fff;
}
public String getGgg() {
return ggg;
}
public void setGgg(String ggg) {
this.ggg = ggg;
}
public Integer getHhh() {
return hhh;
}
public void setHhh(Integer hhh) {
this.hhh = hhh;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
Repository method used for persisting the list of Parent Entity
#Value("${spring.jpa.hibernate.jdbc.batch_size}")
private int batchSize;
public <T extends Parent> Collection<T> bulkSave(Collection<T> entities) {
final List<T> savedEntities = new ArrayList<T>(entities.size());
int i = 0;
for (T t : entities) {
savedEntities.add(persistOrMerge(t));
i++;
if (i % batchSize == 0) {
// Flush a batch of inserts and release memory.
entityManager.flush();
entityManager.clear();
}
}
return savedEntities;
}
private <T extends Parent> T persistOrMerge(T t) {
if (t.getTimeSlotId() == null) {
entityManager.persist(t);
return t;
} else {
return entityManager.merge(t);
}
}
application.yml
spring:
application:
name: sample-service
jpa:
database: MYSQL
show-sql: true
hibernate:
ddl-auto: update
dialect: org.hibernate.dialect.MySQL5Dialect
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
jdbc:
batch_size: 100
jackson:
date-format: dd/MM/yyyy
thymeleaf:
cache: false
spring.datasource.url : jdbc:mysql://${dbhost}/sample?createDatabaseIfNotExist=true
spring.datasource.username : root
spring.datasource.password : root
spring.datasource.driver-class-name : com.mysql.cj.jdbc.Driver
To enable batch insert you need the batch_size property which you have in your configuration.
Also since a jdbc batch can target one table only you need the spring.jpa.hibernate.order_inserts=true property to order the insert between parent and child or else the statement are unordered and you will see a partial batch (new batch anytime an insert in a different table is called)

JPA OneToOne cascade delete

i have a rellationship between 2 classes Document and Medecin
#Entity
public class Document implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String annee;
private Date dateVisite;
private String secteur;
private String typeVisite;
#OneToOne( fetch=FetchType.LAZY,cascade=CascadeType.REMOVE)
#JoinColumn(name = "idMedecin")
private Medecin medecin;
public Document(String annee,
Date dateVisite, String secteur, String typeVisite) {
super();
this.annee = annee;
this.dateVisite = dateVisite;
this.secteur = secteur;
this.typeVisite = typeVisite;
}
public String getSecteur() {
return secteur;
}
public void setSecteur(String secteur) {
this.secteur = secteur;
}
public String getTypeVisite() {
return typeVisite;
}
public void setTypeVisite(String typeVisite) {
this.typeVisite = typeVisite;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAnnee() {
return annee;
}
public void setAnnee(String annee) {
this.annee = annee;
}
public Date getDateVisite() {
return dateVisite;
}
public void setDateVisite(Date dateVisite) {
this.dateVisite = dateVisite;
}
}
and the medecin entity is
#Entity
public class Medecin implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String nom;
private String secteur;
private int telephone;
private int specialite;
public Medecin() {
super();
// TODO Auto-generated constructor stub
}
public Medecin(String nom, String secteur, int telephone, int specialite) {
super();
this.nom = nom;
this.secteur = secteur;
this.telephone = telephone;
this.specialite = specialite;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSecteur() {
return secteur;
}
public void setSecteur(String secteur) {
this.secteur = secteur;
}
public int getTelephone() {
return telephone;
}
public void setTelephone(int telephone) {
this.telephone = telephone;
}
public int getSpecialite() {
return specialite;
}
public void setSpecialite(int specialite) {
this.specialite = specialite;
}
}
the problem is that after i generate the database i want if i delete the document record from the database i want the medecin record will be deleted also but in my case if i delete the document record the medecin record dont be deleted
Based on your configuration, Hibernate will generate Document table with foreign key pointing to Medicine table.
To achieve your requirement, it should be like:
public class Document {
#OneToOne(mappedBy = "document", cascade = CascadeType.REMOVE)
private Medicine medicine;
}
public class Medicine {
#OneToOne
private Document document;
}
Updated
public void delete(int id){
Document document = entityManager.find(Document.class, id);
entityManager.remove(document);
entityManager.flush();
}

JavaFX properties fail to persist

I'm using some JavaFX properties in my app:
#Entity(name = "Klanten")
#Table(name = "Klanten")
#NamedQueries({
#NamedQuery(name = "Klanten.findAll", query = "select k from Klanten k")
})
public class Klant implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int klantId;
#Transient
private final SimpleStringProperty naam = new SimpleStringProperty();
//private String naam;
//private String straat;
#Transient
private final SimpleStringProperty straat = new SimpleStringProperty();
private String telefoon;
private String huisnummer;
private String gsm;
private String woonplaats;
private String email;
private String postcode;
#OneToMany(mappedBy = "Klant", cascade = CascadeType.REMOVE)
private List<Raam> ramen;
public Klant() {
}
public Klant(String naam) {
this.naam.set(naam);
}
#Override
public String toString() {
return this.naam.get();
}
#Access(AccessType.PROPERTY)
#Column(name="naam")
public String getNaam() {
return this.naam.get();
}
public void setNaam(String naam){
this.naam.set(naam);
}
public List<Raam> getRamen() {
return this.ramen;
}
#Id
public int getKlantId() {
return klantId;
}
public void setKlantId(int klantId) {
this.klantId = klantId;
}
#Access(AccessType.PROPERTY)
#Column(name="straat")
public String getStraat() {
return straat.get();
}
public void setStraat(String straat) {
this.straat.set(straat);
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer(String huisnummer) {
this.huisnummer = huisnummer;
}
public String getGsm() {
return gsm;
}
public void setGsm(String gsm) {
this.gsm = gsm;
}
public String getWoonplaats() {
return woonplaats;
}
public void setWoonplaats(String woonplaats) {
this.woonplaats = woonplaats;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public StringProperty naamProperty() {
return naam;
}
public StringProperty straatProperty() {
return straat;
}
}
However when I let JPA generate my database, the column "naam" and "straat" aren't generated. I get no error. How can I resolve this?
I tried all the things listed here:
Possible solution 1
Possible solution 2
These didn't work.
You can try to use regular properties and then have another get method which returns a new SimpleStringProperty, i.e.:
public StringProperty naamProperty() {
return new SimpleStringProperty(naam);
}
public StringProperty straatProperty() {
return new SimpleStringProperty(straat);
}

Entity Manager: em.merge() creates a new record instead of updating

I was developing an EJB application using netbeans which manages Hotel Bookings. I realised that the em.merge() function of the Entity manager inserts a new record in the database instead of updating if the primary key or the #Id of the entity is set to autogenerated.
I have two entities - Booking and Room. The ID for Booking is autogenerated whereas for Room its not autogenerated. The same merge() function in the session bean inserts a new row for Booking but updates for Room.
My Entity beans and session beans are as follows:-
Booking Entity
#SequenceGenerator(name="booking_seq", initialValue=1, allocationSize=100)
#Entity
#NamedQueries({#NamedQuery(name="Booking.getAll",query="SELECT e FROM Booking e order by e.bookingId")})
public class Booking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="booking_seq")
#Column
private int bookingId;
#Column
private int roomId;
#Column
private int customerId;
#Column
#Temporal(javax.persistence.TemporalType.DATE)
private Date arrival_date;
#Column
#Temporal(javax.persistence.TemporalType.DATE)
private Date departure_date;
public Booking(int bookingId, int roomId, int customerId, Date arrival_date, Date departure_date) {
this.bookingId = bookingId;
this.roomId = roomId;
this.customerId = customerId;
this.arrival_date = arrival_date;
this.departure_date = departure_date;
}
public Booking() {
}
public int getBookingId() {
return bookingId;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public int getRoomId() {
return roomId;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public Date getArrival_date() {
return arrival_date;
}
public void setArrival_date(Date arrival_date) {
this.arrival_date = arrival_date;
}
public Date getDeparture_date() {
return departure_date;
}
public void setDeparture_date(Date departure_date) {
this.departure_date = departure_date;
}
}
Room Entity
#Entity
#Table
#NamedQueries({#NamedQuery(name="Room.getAll",query="SELECT e FROM Room e order by e.roomId")})
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column
private int roomId;
#Column
private String roomType;
#Column
private String bedType;
#Column
private double tariff;
public Room() {
}
public Room(int roomId, String roomType, String bedType, double tariff) {
this.roomId = roomId;
this.roomType = roomType;
this.bedType = bedType;
this.tariff = tariff;
}
public int getRoomId() {
return roomId;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getBedType() {
return bedType;
}
public void setBedType(String bedType) {
this.bedType = bedType;
}
public double getTariff() {
return tariff;
}
public void setTariff(double tariff) {
this.tariff = tariff;
}
}
The session bean for Booking Entity
#Stateless
public class BookingDAO implements BookingDAOLocal {
#PersistenceContext
private EntityManager em;
#Override
public void addBooking(Booking booking) {
em.persist(booking);
}
#Override
public void editBooking(Booking booking) {
em.merge(booking);
}
#Override
public void deleteBooking(int bookingId) {
em.remove(em.find(Booking.class, bookingId));
}
}
The session bean for Room Entity
#Stateless
public class RoomDAO implements RoomDAOLocal {
#PersistenceContext
private EntityManager em;
#Override
public void addRoom(Room room) {
em.merge(room);
em.flush();
}
#Override
public void editRoom(Room room) {
em.merge(room);
em.flush();
}
#Override
public void deleteRoom(int roomId) {
em.remove(em.find(Room.class, roomId));
}
}
Actually i got the answer now. For the editBooking() method i was using the same code as addBooking(). In addBooking() i didnt have the setBookingId() method call as it was autogenerated. Just needed to add the extra part for edit method.
else if ("Add".equalsIgnoreCase(action) || "Edit".equalsIgnoreCase(action) )
{
try {
arrival_date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(request.getParameter("arrival_date"));
departure_date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(request.getParameter("departure_date"));
}
catch(ParseException e) {
e.printStackTrace();
}
Booking booking = new Booking();
if("Edit".equalsIgnoreCase(action))
{
int bookingId=Integer.parseInt(request.getParameter("bookingId"));
booking.setBookingId(bookingId);
}
booking.setRoomId(Integer.parseInt(request.getParameter("roomId")));
booking.setCustomerId(customerId);
booking.setArrival_date(arrival_date);
booking.setDeparture_date(departure_date);
if("Add".equalsIgnoreCase(action))
bookingDao.addBooking(booking);
else
bookingDao.editBooking(booking);
request.setAttribute("allBookings", bookingDao.getAllBookings());
request.getRequestDispatcher("booking_details.jsp").forward(request, response);
}
You are not trying to updating the record, you re trying to persisting the same room instead of try this.
#Override
public void editRoom(Room room) {
Room r-= em.merge(room);
r.setRoomType("2bed"); // your own update field other than the #Id (Primary key)
em.flush();
// you can retun the updated employee.
}