I am currently developing a Java EE application using hibernate as ORM.
I am using the DAO design pattern. I want to delete a row from the contact table but I don't know why it is not working. When I delete société it works.
I have a relation between société and contact. When a contact has idSociéte=null it is deleted, but if it exist it will not delete it. When I did delete in phpmysadmin it works even if idSociété not null.
#Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
#PersistenceContext
private EntityManager em;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public Class<T> getDaoType() {
return daoType;
}
public void setDaoType(Class<T> daoType) {
this.daoType = daoType;
}
public void insert(T t) {
// TODO Auto-generated method stub
em.persist(t);
}
public void update(T t) {
// TODO Auto-generated method stub
em.merge(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
Object managed = em.merge(t);
em.remove(managed);
}
public T findById(Class<T> t, int id) {
// TODO Auto-generated method stub
return em.find(daoType, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
return (List<T>) query.getResultList();
}
}
package biz.picosoft.entity;
#Entity
#Table(name = "Contacte")
public class Contacte implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idContact")
int idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
#ManyToOne
#JoinColumn(name = "société_id")
private Société société;
public Contacte() {
super();
}
public long getIdContact() {
return idContact;
}
public Contacte(String nom, String mail, String téléphone, String adresse, Société société) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
this.société = société;
}
public Contacte(int idContact, String nom, String mail, String téléphone, String adresse, Société société) {
super();
this.idContact = idContact;
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
this.société = société;
}
public void setIdContact(int idContact) {
this.idContact = idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
public Société getSociété() {
return société;
}
public void setSociété(Société société) {
this.société = société;
}
}
package biz.picosoft.daoImpl;
#Component
public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao {
}
package biz.picosoft.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity(name = "société")
#Table(name="société")
public class Société implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idSociété")
int idSociété;
#Column(name = "nom")
String nom;
#Column(name = "email")
String email;
#Column(name = "télèphone")
String télèphone;
#Column(name = "adress")
String adress;
#OneToMany (fetch = FetchType.EAGER,mappedBy = "société", cascade = CascadeType.ALL)
private List<Contacte> contacts;
public Société(String nom, String email, String télèphone, String adress) {
super();
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
}
public Société(int idSociété, String nom, String email, String télèphone, String adress) {
super();
this.idSociété = idSociété;
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
this.contacts = contacts;
}
public Société() {
super();
}
public int getIdSociété() {
return idSociété;
}
public void setIdSociété(int idSociété) {
this.idSociété = idSociété;
}
#Column(name = "nom")
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTélèphone() {
return télèphone;
}
public void setTélèphone(String télèphone) {
this.télèphone = télèphone;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public List<Contacte> getContacts() {
return contacts;
}
public void setContacts(List<Contacte> contacts) {
this.contacts = contacts;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idSociété;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Société other = (Société) obj;
if (idSociété != other.idSociété)
return false;
return true;
}
}
when a contact has idSociéte=null it is deleted but if it exist it
will not delete it.
It means if the idSociete is not null and have some value for eg. 123. You need to check if any of the contact have the same idSociete. if it's present with any other contact then your contact will not be deleted as Many contacts can be associated with same société. Try with single contact and a single société associated with it.
Related
Need help when trying to save through this method, my hibernate debug doesn't show any error, no one error catch in this method
it is not committed, already try everything includes saveAndFlush() from JPARepositiry, all possible annotation, check whole my algorithm and logic. I thought it's related to my PostgreSQL configuration or my bidirectional relationship between related entities. But still, nothing showed up on my table in the database
#RequestMapping(value = "/save-pegawai-status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePlanningPegawaiStatus(#Valid #RequestBody PlanningPegawaiStatusVO vo,
HttpServletRequest request) {
try {
Map<String, Object> result = servicePermohonanStatus.savePlanningPegawaiStatus(vo);
if (CommonUtil.isNotNullOrEmpty(result.get("noRec"))) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
} else {
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
} catch (Exception exp) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", exp.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, exp.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="ListTanggalCuti_T")
public class ListTanggalCuti extends BaseTransaction{
#Caption(value="tgl")
#Column(name="tgl", nullable=true)
private Date tgl;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Boolean approvalStatus;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Planning Pegawai Status")
#JoinColumn(name="ObjectPlanningPegawaiStatusFK")
private PlanningPegawaiStatus planningPegawaiStatus;
#Column(name="ObjectPlanningPegawaiStatusFK", insertable=false, updatable=false)
private String planningPegawaiStatusId;
public Date getTgl() {
return tgl;
}
public void setTgl(Date tgl) {
this.tgl = tgl;
}
public Boolean getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Boolean approvalStatus) {
this.approvalStatus = approvalStatus;
}
public PlanningPegawaiStatus getPlanningPegawaiStatus() {
return planningPegawaiStatus;
}
public void setPlanningPegawaiStatus(PlanningPegawaiStatus planningPegawaiStatus) {
this.planningPegawaiStatus = planningPegawaiStatus;
}
public String getPlanningPegawaiStatusId() {
return planningPegawaiStatusId;
}
public void setPlanningPegawaiStatusId(String planningPegawaiStatusId) {
this.planningPegawaiStatusId = planningPegawaiStatusId;
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="PlanningPegawaiStatus_T")
public class PlanningPegawaiStatus extends BaseTransaction{
#Caption(value="No Planning")
#Column(name="NoPlanning", length=15, nullable=true)
private String noPlanning;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Pegawai")
#JoinColumn(name="ObjectPegawaiFk")
private Pegawai pegawai;
// #ManyToOne(fetch=FetchType.LAZY)
// #Caption(value="Object Jabatan Cuti")
// #JoinColumn(name="ObjectJabatanCutiFk")
// private Jabatan jabatanCuti;
#Column(name="ObjectPegawaiFk", nullable=true, insertable=false, updatable=false)
private Integer pegawaiId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Plan")
#JoinColumn(name="ObjectStatusPegawaiPlanFk")
private StatusPegawai statusPegawaiPlan;
#Column(name="ObjectStatusPegawaiPlanFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiPlanId;
#OneToMany(cascade=CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = "planningPegawaiStatus", orphanRemoval=true)
private Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Departemen")
#JoinColumn(name="ObjectDepartemenFk")
private Departemen departemen;
#Column(name="ObjectDepartemenFk", nullable=true, insertable=false, updatable=false)
private Integer departemenId;
#Caption(value="Deskripsi Status Pegawai Plan")
#Column(name="DeskripsiStatusPegawaiPlan", length=1000, nullable=true)
private String deskripsiStatusPegawaiPlan;
#Caption(value="Keterangan Lainya Plan")
#Column(name="KeteranganLainyaPlan", length=1000, nullable=true)
private String keteranganLainyaPlan;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object No SK")
#JoinColumn(name="ObjectNoSkFk")
private SuratKeputusan noSk;
#Column(name="ObjectNoSkFk", nullable=true, insertable=false, updatable=false)
private Integer noSkId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Exec")
#JoinColumn(name="ObjectStatusPegawaiExecFk")
private StatusPegawai statusPegawaiExec;
#Column(name="ObjectStatusPegawaiExecFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiExecId;
#Caption(value="Deskripsi Status Pegawai Exec")
#Column(name="DeskripsiStatusPegawaiExec", length=1000, nullable=true)
private String deskripsiStatusPegawaiExec;
#Caption(value="Keterangan Lainya Exec")
#Column(name="KeteranganLainyaExec", length=1000, nullable=true)
private String keteranganLainyaExec;
#Caption(value="Tgl Pengajuan")
#Column(name="TglPengajuan", nullable=true)
private Date tglPengajuan;
#Caption(value="Tgl Keputusan")
#Column(name="TglKeputusan", nullable=true)
private Date tglKeputusan;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Integer approvalStatus;
#Caption(value="jumlahHari")
#Column(name="jumlahHari", nullable=true)
private Integer jumlahHari;
// #Caption(value="keterangan")
// #Column(name="keterangan", nullable=true)
// private String keterangan;
#Caption(value="Jenis Perawatan")
#Column(name="jenisPerawatan", nullable=true)
private Integer jenisPerawatan;
#Caption(value="Alamat Selama Cuti")
#Column(name="alamatCuti", nullable=true)
private String alamatCuti;
#Caption(value="Nomor Telepon")
#Column(name="nomorTelepon", nullable=true)
private String nomorTelepon;
#Caption(value="Nomor Surat Tugas")
#Column(name="noSuratTugas", nullable=true)
private String noSuratTugas;
#Caption(value="Nomor Nota Dinas")
#Column(name="noNotaDinas", nullable=true)
private String noNotaDinas;
#Caption(value="Tgl Nota Dinas")
#Column(name="TglNotaDinas", nullable=true)
private Date tglNotaDinas;
#Caption(value="Alamat Tugas Dinas")
#Column(name="alamatTugas", nullable=true)
private String alamatTugas;
#ManyToOne(optional=true,fetch=FetchType.LAZY)
#Caption(value="Object Jabatan Pemberi Nota Dinas")
#JoinColumn(name="ObjectJabatanPemberiNotaDinasFk", nullable=true)
private Jabatan jabatanPemberiNotaDinas;
#Column(name="ObjectJabatanPemberiNotaDinasFk", nullable=true, insertable=false, updatable=false)
private Integer jabatanIdPemberiNotaDinas;
#Caption(value="is Cuti Luar Negeri")
#Column(name="isCutiLuarNegeri", nullable=true)
private Boolean isCutiLuarNegeri;
public String getNoPlanning() {
return noPlanning;
}
public void setNoPlanning(String noPlanning) {
this.noPlanning = noPlanning;
}
public Pegawai getPegawai() {
return pegawai;
}
public void setPegawai(Pegawai pegawai) {
this.pegawai = pegawai;
}
public Integer getPegawaiId() {
return pegawaiId;
}
public void setPegawaiId(Integer pegawaiId) {
this.pegawaiId = pegawaiId;
}
// public Jabatan getJabatanCuti() {
// return jabatanCuti;
// }
// public void setJabatanCuti(Jabatan jabatanCuti) {
// this.jabatanCuti = jabatanCuti;
// }
public StatusPegawai getStatusPegawaiPlan() {
return statusPegawaiPlan;
}
public void setStatusPegawaiPlan(StatusPegawai statusPegawaiPlan) {
this.statusPegawaiPlan = statusPegawaiPlan;
}
public Integer getStatusPegawaiPlanId() {
return statusPegawaiPlanId;
}
public void setStatusPegawaiPlanId(Integer statusPegawaiPlanId) {
this.statusPegawaiPlanId = statusPegawaiPlanId;
}
public Departemen getDepartemen() {
return departemen;
}
public void setDepartemen(Departemen departemen) {
this.departemen = departemen;
}
public Integer getDepartemenId() {
return departemenId;
}
public void setDepartemenId(Integer departemenId) {
this.departemenId = departemenId;
}
public String getDeskripsiStatusPegawaiPlan() {
return deskripsiStatusPegawaiPlan;
}
public void setDeskripsiStatusPegawaiPlan(String deskripsiStatusPegawaiPlan) {
this.deskripsiStatusPegawaiPlan = deskripsiStatusPegawaiPlan;
}
public String getKeteranganLainyaPlan() {
return keteranganLainyaPlan;
}
public void setKeteranganLainyaPlan(String keteranganLainyaPlan) {
this.keteranganLainyaPlan = keteranganLainyaPlan;
}
public SuratKeputusan getNoSk() {
return noSk;
}
public void setNoSk(SuratKeputusan noSk) {
this.noSk = noSk;
}
public Integer getNoSkId() {
return noSkId;
}
public void setNoSkId(Integer noSkId) {
this.noSkId = noSkId;
}
public StatusPegawai getStatusPegawaiExec() {
return statusPegawaiExec;
}
public void setStatusPegawaiExec(StatusPegawai statusPegawaiExec) {
this.statusPegawaiExec = statusPegawaiExec;
}
public Integer getStatusPegawaiExecId() {
return statusPegawaiExecId;
}
public void setStatusPegawaiExecId(Integer statusPegawaiExecId) {
this.statusPegawaiExecId = statusPegawaiExecId;
}
public String getDeskripsiStatusPegawaiExec() {
return deskripsiStatusPegawaiExec;
}
public void setDeskripsiStatusPegawaiExec(String deskripsiStatusPegawaiExec) {
this.deskripsiStatusPegawaiExec = deskripsiStatusPegawaiExec;
}
public String getKeteranganLainyaExec() {
return keteranganLainyaExec;
}
public void setKeteranganLainyaExec(String keteranganLainyaExec) {
this.keteranganLainyaExec = keteranganLainyaExec;
}
public Date getTglPengajuan() {
return tglPengajuan;
}
public void setTglPengajuan(Date tglPengajuan) {
this.tglPengajuan = tglPengajuan;
}
public Date getTglKeputusan() {
return tglKeputusan;
}
public void setTglKeputusan(Date tglKeputusan) {
this.tglKeputusan = tglKeputusan;
}
public Integer getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Integer approvalStatus) {
this.approvalStatus = approvalStatus;
}
public Integer getJumlahHari() {
return jumlahHari;
}
public void setJumlahHari(Integer jumlahHari) {
this.jumlahHari = jumlahHari;
}
public Set<ListTanggalCuti> getListTanggal() {
return listTanggal;
}
public void setListTanggal(Set<ListTanggalCuti> listTanggal) {
this.listTanggal = listTanggal;
}
// public String getKeterangan() {
// return keterangan;
// }
// public void setKeterangan(String keterangan) {
// this.keterangan = keterangan;
// }
public Integer getJenisPerawatan() {
return jenisPerawatan;
}
public void setJenisPerawatan(Integer jenisPerawatan) {
this.jenisPerawatan = jenisPerawatan;
}
public String getAlamatCuti() {
return alamatCuti;
}
public void setAlamatCuti(String alamatCuti) {
this.alamatCuti = alamatCuti;
}
public String getNomorTelepon() {
return nomorTelepon;
}
public void setNomorTelepon(String nomorTelepon) {
this.nomorTelepon = nomorTelepon;
}
public String getNoSuratTugas() {
return noSuratTugas;
}
public void setNoSuratTugas(String noSuratTugas) {
this.noSuratTugas = noSuratTugas;
}
public String getNoNotaDinas() {
return noNotaDinas;
}
public void setNoNotaDinas(String noNotaDinas) {
this.noNotaDinas = noNotaDinas;
}
public Date getTglNotaDinas() {
return tglNotaDinas;
}
public void setTglNotaDinas(Date tglNotaDinas) {
this.tglNotaDinas = tglNotaDinas;
}
public String getAlamatTugas() {
return alamatTugas;
}
public void setAlamatTugas(String alamatTugas) {
this.alamatTugas = alamatTugas;
}
public Jabatan getJabatanPemberiNotaDinas() {
return jabatanPemberiNotaDinas;
}
public void setJabatanPemberiNotaDinas(Jabatan jabatanPemberiNotaDinas) {
this.jabatanPemberiNotaDinas = jabatanPemberiNotaDinas;
}
public Integer getJabatanIdPemberiNotaDinas() {
return jabatanIdPemberiNotaDinas;
}
public void setJabatanIdPemberiNotaDinas(Integer jabatanIdPemberiNotaDinas) {
this.jabatanIdPemberiNotaDinas = jabatanIdPemberiNotaDinas;
}
public Boolean getIsCutiLuarNegeri() {
return isCutiLuarNegeri;
}
public void setIsCutiLuarNegeri(Boolean isCutiLuarNegeri) {
this.isCutiLuarNegeri = isCutiLuarNegeri;
}
}
#Override
#Transactional
public Map<String, Object> savePlanningPegawaiStatus(PlanningPegawaiStatusVO vo) {
Map<String, Object> result = new HashMap<>();
boolean statusTanggalPermohonan = validateTanggalPermohonan(vo.getListTanggal(), vo.getPegawai().getId());
if (CommonUtil.isNotNullOrEmpty(statusTanggalPermohonan) && !statusTanggalPermohonan) {
result.put("bisaCuti", statusTanggalPermohonan);
result.put("status", "Tanggal Permohonan sudah pernah diajukan!"); //Validasi tanggal permohonan yang sudah diajukan
return result;
} else {
Integer day = 0;
if (CommonUtil.isNotNullOrEmpty(vo)) {
PlanningPegawaiStatus planningPegawaiStatus = planningPegawaiStatusConverter.transferVOToModel(vo,
new PlanningPegawaiStatus());
String noPlanning = noUsulan().get("noUsulan").toString();
if (CommonUtil.isNotNullOrEmpty(noPlanning)) {
planningPegawaiStatus.setNoPlanning(noPlanning);
planningPegawaiStatus.setStatusEnabled(true);
if (CommonUtil.isNotNullOrEmpty(vo.getStatusPegawaiPlan())) {
planningPegawaiStatus.setStatusPegawaiPlan(
statusPegawaiConverter.transferVOToModel(vo.getStatusPegawaiPlan(), new StatusPegawai()));
}
if (CommonUtil.isNotNullOrEmpty(vo.getJabatanPemberiNotaDinas())) {
planningPegawaiStatus.setJabatanPemberiNotaDinas(
jabatanConverter.transferVOToModel(vo.getJabatanPemberiNotaDinas(), new Jabatan()));
}
planningPegawaiStatus.setApprovalStatus(0);
if (CommonUtil.isNotNullOrEmpty(vo.getPegawai())) {
planningPegawaiStatus
.setPegawai(pegawaiConverter.transferVOToModel(vo.getPegawai(), new Pegawai()));
}
Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
for (ListTanggalCutiVO date : vo.getListTanggal()) {
day++;
ListTanggalCuti tanggal = listTanggalConverter.transferVOToModel(date, new ListTanggalCuti());
tanggal.setPlanningPegawaiStatus(planningPegawaiStatus);
tanggal.setStatusEnabled(true);
listTanggal.add(tanggal);
}
planningPegawaiStatus.setJumlahHari(day);
planningPegawaiStatus.setListTanggal(listTanggal);
if (CommonUtil.isNotNullOrEmpty(vo.getDeskripsiStatusPegawaiPlan())) {
planningPegawaiStatus.setDeskripsiStatusPegawaiPlan(vo.getDeskripsiStatusPegawaiPlan());
}
if (CommonUtil.isNotNullOrEmpty(vo.getKeteranganLainyaPlan())) {
planningPegawaiStatus.setKeteranganLainyaPlan(vo.getKeteranganLainyaPlan());
}
//Set Alamat Cuti dan No Telepon
planningPegawaiStatus.setAlamatCuti(vo.getAlamatCuti());
planningPegawaiStatus.setNomorTelepon(vo.getNomorTelepon());
if (CommonUtil.isNotNullOrEmpty(vo.getAlamatTugas())) {
planningPegawaiStatus.setAlamatTugas(vo.getAlamatTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoSuratTugas())) {
planningPegawaiStatus.setNoSuratTugas(vo.getNoSuratTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoNotaDinas())) {
planningPegawaiStatus.setNoNotaDinas(vo.getNoNotaDinas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getTglNotaDinas())) {
planningPegawaiStatus.setTglNotaDinas(vo.getTglNotaDinas());
}
planningPegawaiStatus.setIsCutiLuarNegeri(vo.getIsCutiLuarNegeri());
if (CommonUtil.isNotNullOrEmpty(planningPegawaiStatus)) {
List<String> listTgl = new ArrayList<>();
planningPegawaiStatus.setStatusEnabled(true);
PlanningPegawaiStatus planningPegawaiStatusResult = planningPegawaiStatusDao
.save(planningPegawaiStatus);
for (ListTanggalCuti listTanggalCuti : planningPegawaiStatusResult.getListTanggal()) {
listTgl.add(listTanggalCuti.getNoRec());
}
result.put("listTgl", listTgl);
result.put("noRec", planningPegawaiStatusResult.getNoRec());
result.put("bisaCuti", statusTanggalPermohonan);
}
}
}
return result;
}
}
PlanningPegawaiStatusVO and ListTanggalCutiVO just related value object class, transferVOToModel() is a method for data access from value object class to model
I'm finally realized that sometimes its commit and sometimes it isn't. And then when it isn't inserted to the database, also return with HttpStatus.CREATED an ERROR_MESSAGE like could not extract ResultSet from GenericJDBCException but it does not come from catch
I'm trying to implement authentication with Spring Security and my problem is that I'm using a MongoDB base where the username and the associated password are in two distinct collections. So when I implement UserDetails, I can't return the password properly. Here is what I've tried:
package com.example.springmongo.user;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Document(collection = "users")
public class User implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -2217225560457250699L;
#Autowired
private UserPassService userPassService;
#Id
private String id;
#Field(value = "iduser")
private Long iduser;
#Field(value = "name_complete")
private String name_complete;
#Field(value = "mail")
private String mail;
#Field(value = "active")
private Double active;
#Field(value = "creationDate")
private String creationDate;
#Field(value = "last_login")
private String last_login;
public User() {
super();
}
public User(String id, Long iduser, String name_complete, String mail, Double active, String creationDate, String last_login) {
super();
this.id = id;
this.iduser = iduser;
this.name_complete = name_complete;
this.mail = mail;
this.active = active;
this.creationDate = creationDate;
this.last_login = last_login;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getIduser() {
return iduser;
}
public void setIduser(Long iduser) {
this.iduser = iduser;
}
public String getName_complete() {
return name_complete;
}
public void setName_complete(String name_complete) {
this.name_complete = name_complete;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Double getActive() {
return active;
}
public void setActive(Double active) {
this.active = active;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getLast_login() {
return last_login;
}
public void setLast_login(String last_login) {
this.last_login = last_login;
}
#Override
public String toString() {
return "name: " + this.name_complete + ", mail: " + this.mail + ", id: " + this.id;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getPassword() {
return this.userPassService.getUserPassword(this.iduser);
}
#Override
public String getUsername() {
return this.getMail();
}
#Override
public boolean isAccountNonExpired() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isAccountNonLocked() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isCredentialsNonExpired() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isEnabled() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
}
Unfortunately, I can't access my UserPassService from an entity like this. So how can I access the password ?
Thanks in advance !
You cant use #Autowired on spring components in entity class as a field. Use like this ;
private transient UserPassService userPassService;
and add setter method of this ;
#Autowired
public void setUserPassService(UserPassService userPassService) {
this.userPassService = userPassService;
}
Beaware of creatation of Entity class with new is making this service is null. If you create with new , call setUserPassService method with autowired object of UserPassService.
I have an entity question and an entity test with ManyToMany relationship between the two entitie.
when I want to view the questions of a test this error is occurred.
failed to lazily initialize a collection of role:
tn.esen.entities.Test.questions, could not initialize proxy - no Session
this is the JPA implementation of the two entities.
Question:
package tn.esen.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
#Entity
public class Question implements Serializable {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contenu == null) ? 0 :
contenu.hashCode());
result = prime * result + ((dateCreation == null) ? 0 :
dateCreation.hashCode());
result = prime * result + ((niveauDeDifficulte == null) ? 0 :
niveauDeDifficulte.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Question other = (Question) obj;
if (contenu == null) {
if (other.contenu != null)
return false;
} else if (!contenu.equals(other.contenu))
return false;
if (dateCreation == null) {
if (other.dateCreation != null)
return false;
} else if (!dateCreation.equals(other.dateCreation))
return false;
if (niveauDeDifficulte == null) {
if (other.niveauDeDifficulte != null)
return false;
} else if (!niveauDeDifficulte.equals(other.niveauDeDifficulte))
return false;
return true;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_question")
private int id;
private String contenu;
private String niveauDeDifficulte;
private Date dateCreation;
#OneToMany(mappedBy="question",fetch = FetchType.EAGER)
private Collection <Reponse> reponses;
#ManyToOne
private Categorie categorie;
#ManyToOne
private Administrateur administrateur;
#ManyToMany(mappedBy = "questions",fetch = FetchType.EAGER)
private Collection<Test> tests;
public Question(){
super();
}
#Override
public String toString() {
return "Question [id=" + id + ", contenu=" + contenu + ",
niveauDeDifficulte=" + niveauDeDifficulte + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
public String getNiveauDeDifficulte() {
return niveauDeDifficulte;
}
public void setNiveauDeDifficulte(String niveauDeDifficulte) {
this.niveauDeDifficulte = niveauDeDifficulte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Collection<Reponse> getReponses() {
return reponses;
}
public void setReponses(Collection<Reponse> reponses) {
this.reponses = reponses;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Administrateur getAdministrateur() {
return administrateur;
}
public void setAdministrateur(Administrateur administrateur) {
this.administrateur = administrateur;
}
public Collection<Test> getTest() {
return tests;
}
public void setTest(Collection<Test> tests) {
this.tests = tests;
}
public Question(String contenu, String niveauDeDifficulte, Date
dateCreation) {
super();
this.contenu = contenu;
this.niveauDeDifficulte = niveauDeDifficulte;
this.dateCreation = dateCreation;
}
Test:
package tn.esen.entities;
#Entity
public class Test implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String duree;
private String typeDePreparation;
private String lieu;
private int nbrQuestionFacile;
private int nbrQuestionMoyen;
private int nbrQuestionDifficle;
#OneToMany(mappedBy = "test")
private Collection<Resultat> resultats;
#ManyToMany
private Collection<Question> questions;
#ManyToOne
private ResponsableTechnique responsableTechnique;
public Test() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDuree() {
return duree;
}
public void setDuree(String duree) {
this.duree = duree;
}
public Collection<Question> getQuestions() {
return questions;
}
public void setQuestions(Collection<Question> questions) {
this.questions = questions;
}
public Test(String duree, String typeDePreparation, String lieu, int
nbrQuestionFacile, int nbrQuestionMoyen,
int nbrQuestionDifficle) {
super();
this.duree = duree;
this.typeDePreparation = typeDePreparation;
this.lieu = lieu;
this.nbrQuestionFacile = nbrQuestionFacile;
this.nbrQuestionMoyen = nbrQuestionMoyen;
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public ResponsableTechnique getRésponsableTechnique() {
return responsableTechnique;
}
public void setRésponsableTechnique(ResponsableTechnique
résponsableTechnique) {
this.responsableTechnique = résponsableTechnique;
}
public String getTypeDePreparation() {
return typeDePreparation;
}
public void setTypeDePreparation(String typeDePreparation) {
this.typeDePreparation = typeDePreparation;
}
public String getLieu() {
return lieu;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
public int getNbrQuestionFacile() {
return nbrQuestionFacile;
}
public void setNbrQuestionFacile(int nbrQuestionFacile) {
this.nbrQuestionFacile = nbrQuestionFacile;
}
public int getNbrQuestionMoyen() {
return nbrQuestionMoyen;
}
public void setNbrQuestionMoyen(int nbrQuestionMoyen) {
this.nbrQuestionMoyen = nbrQuestionMoyen;
}
public int getNbrQuestionDifficle() {
return nbrQuestionDifficle;
}
public void setNbrQuestionDifficle(int nbrQuestionDifficle) {
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public Collection<Resultat> getResultats() {
return resultats;
}
public void setRésultats(Collection<Resultat> resultats) {
this.resultats = resultats;
}
}
}
When you get Test and access Test.questions later, after leaving the transaction, you will get a lazy initialization exception when the Test entity is detached and questions has not been initialized/fetched yet. You can either do a specific fetch, or depending on your configuration, you can call Test.getQuestions().size() before you exit the transaction.
References: How to solve lazy initialization exception using JPA and Hibernate as provider
LazyInitializationException in JPA and Hibernate
Hibernate LazyInitializationException using Spring CrudRepository
i'm trying to develop a function that count number of rows with specific arguments: for example i want to count the number of dossier which the client is 'client a' i want to get it in a table the first case contain the name of client and the second contanint the number of dossier
for example
client a |5
client b |12
....
right now i just wrote a function that returns the number of all rows
public Object countrow(){
Query query=em.createQuery("SELECT COUNT(d) FROM Dossier d");
Object resultat= query.getSingleResult();
System.out.println(resultat);
return resultat;
}
here's my entity named dossier :
package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#NamedQueries({ #NamedQuery(name = "Dossier.findAll", query = "select o from Dossier o") })
public class Dossier implements Serializable {
#Column(name = "CAT_PROB", length = 4000)
private String catProb;
#Column(length = 4000)
private String client;
#Column(length = 4000)
private String contact;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_APPEL")
private Date dateAppel;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_CREATION")
private Date dateCreation;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_FERMERTURE")
private Date dateFermerture;
#Column(name = "DEP_ID", length = 4000)
private String depId;
#Column(name = "DESCRI_PROB", length = 4000)
private String descriProb;
#Column(name = "DUREE_TRAITEMENT")
private Long dureeTraitement;
#Column(length = 4000)
private String etat;
#Column(name = "FINAL", length = 4000)
private String final_;
#Column(name = "HEURE_APPEL", length = 20)
private String heureAppel;
#Column(name = "HEURE_FERMETURE", length = 20)
private String heureFermeture;
#Id
#Column(name = "ID_DOSSIER", nullable = false, length = 4000)
private String idDossier;
#Column(name = "ING_AFF", length = 4000)
private String ingAff;
#Column(length = 4000)
private String motiftemp;
#Column(name = "OUVERT_PAR", length = 4000)
private String ouvertPar;
#Column(name = "TEL_CONTACT")
private BigDecimal telContact;
#Column(name = "TYPE_DOSSIER", length = 4000)
private String typeDossier;
public Dossier() {
}
public Dossier(String catProb, String client, String contact, Date dateAppel, Date dateCreation,
Date dateFermerture, String depId, String descriProb, Long dureeTraitement, String etat,
String final_, String heureAppel, String heureFermeture, String idDossier, String ingAff,
String motiftemp, String ouvertPar, BigDecimal telContact, String typeDossier) {
this.catProb = catProb;
this.client = client;
this.contact = contact;
this.dateAppel = dateAppel;
this.dateCreation = dateCreation;
this.dateFermerture = dateFermerture;
this.depId = depId;
this.descriProb = descriProb;
this.dureeTraitement = dureeTraitement;
this.etat = etat;
this.final_ = final_;
this.heureAppel = heureAppel;
this.heureFermeture = heureFermeture;
this.idDossier = idDossier;
this.ingAff = ingAff;
this.motiftemp = motiftemp;
this.ouvertPar = ouvertPar;
this.telContact = telContact;
this.typeDossier = typeDossier;
}
public String getCatProb() {
return catProb;
}
public void setCatProb(String catProb) {
this.catProb = catProb;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Date getDateAppel() {
return dateAppel;
}
public void setDateAppel(Date dateAppel) {
this.dateAppel = dateAppel;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateFermerture() {
return dateFermerture;
}
public void setDateFermerture(Date dateFermerture) {
this.dateFermerture = dateFermerture;
}
public String getDepId() {
return depId;
}
public void setDepId(String depId) {
this.depId = depId;
}
public String getDescriProb() {
return descriProb;
}
public void setDescriProb(String descriProb) {
this.descriProb = descriProb;
}
public Long getDureeTraitement() {
return dureeTraitement;
}
public void setDureeTraitement(Long dureeTraitement) {
this.dureeTraitement = dureeTraitement;
}
public String getEtat() {
return etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getFinal_() {
return final_;
}
public void setFinal_(String final_) {
this.final_ = final_;
}
public String getHeureAppel() {
return heureAppel;
}
public void setHeureAppel(String heureAppel) {
this.heureAppel = heureAppel;
}
public String getHeureFermeture() {
return heureFermeture;
}
public void setHeureFermeture(String heureFermeture) {
this.heureFermeture = heureFermeture;
}
public String getIdDossier() {
return idDossier;
}
public void setIdDossier(String idDossier) {
this.idDossier = idDossier;
}
public String getIngAff() {
return ingAff;
}
public void setIngAff(String ingAff) {
this.ingAff = ingAff;
}
public String getMotiftemp() {
return motiftemp;
}
public void setMotiftemp(String motiftemp) {
this.motiftemp = motiftemp;
}
public String getOuvertPar() {
return ouvertPar;
}
public void setOuvertPar(String ouvertPar) {
this.ouvertPar = ouvertPar;
}
public BigDecimal getTelContact() {
return telContact;
}
public void setTelContact(BigDecimal telContact) {
this.telContact = telContact;
}
public String getTypeDossier() {
return typeDossier;
}
public void setTypeDossier(String typeDossier) {
this.typeDossier = typeDossier;
}
}
I've been stuck here for almost a week trying find the answer on the internet but sadly nothing worked. :( Everytime I try to update using this method:
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
Im always getting this error:
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.infor.ecom.tenant.manager.model.entity.ApplicationProperty
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:876)
But when Im using this method it works fine:
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
So here is my complete codes:
Tenant.java
package com.infor.ecom.tenant.manager.model.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.infor.ecom.tenant.manager.constant.TenantManagerConstants;
import com.infor.ecom.tenant.manager.constant.TenantStatusEnum;
#Entity
#Table(name="tenant")
#XmlRootElement(name = "Tenant",namespace = "http://com.infor.ecom.tenant.manager/Tenant")
public class Tenant extends BaseModel {
private static final long serialVersionUID = -6687293822212120396L;
#Id
private String id;
private String displayName;
private String description;
private String url;
private String apiKey;
private String status;
#OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Database> databases;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Activity> activites;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Administrator> administrators;
private String message;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<TenantApplicationProperty> tenantApplicationProperties;
#OneToOne(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Product product;
public Database findEcomDatabase() {
Database database = null;
if(databases != null) {
for(Database db : databases) {
if(db.getDatasource() != null) {
if(TenantManagerConstants.ECOM_DATASOURCE.equals(db.getDatasource().getName())) {
database = db;
break;
}
}
}
}
return database;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getStatus() {
return status;
}
public void setStatus(TenantStatusEnum statusEnum) {
this.status = statusEnum.name();
}
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
public void addDatabase(Database database) {
if (this.databases == null) {
this.databases = new ArrayList<Database>();
}
database.setTenant(this);
this.databases.add(database);
}
public List<Activity> getActivites() {
return activites;
}
public void setActivites(List<Activity> activities) {
this.activites = activities;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setStatus(String status) {
this.status = status;
}
public List<Administrator> getAdministrators() {
return this.administrators;
}
public void setAdministrators(List<Administrator> administrators) {
for (Administrator admin:administrators) {
admin.setTenant(this);
}
this.administrators = administrators;
}
public void addAdministrator(Administrator administrator) {
if (this.administrators == null) {
this.administrators = new ArrayList<Administrator>();
}
administrator.setTenant(this);
this.administrators.add(administrator);
}
public List<TenantApplicationProperty> getTenantApplicationProperties() {
return tenantApplicationProperties;
}
public void setTenantApplicationProperties(
List<TenantApplicationProperty> tenantApplicationProperties) {
this.tenantApplicationProperties = tenantApplicationProperties;
}
public void addTenantApplicationProperty(TenantApplicationProperty tenantApplicationProperty) {
if (this.tenantApplicationProperties == null) {
this.tenantApplicationProperties = new ArrayList<TenantApplicationProperty>();
}
tenantApplicationProperty.setTenant(this);
this.tenantApplicationProperties.add(tenantApplicationProperty);
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
product.setTenant(this);
this.product = product;
}
}
TenantApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.infor.ecom.tenant.manager.model.entity.pk.TenantApplicationPropertyPK;
#Entity
#Table(name = "tenant_application_property")
#IdClass(TenantApplicationPropertyPK.class)
public class TenantApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
#Id
#OneToOne
#JoinColumn(name = "application_property_id")
private ApplicationProperty applicationProperty;
private String value;
public TenantApplicationProperty() {
super();
}
/**
* Added constructor to handle custom query for
* findByTenantIdApplicationPropertyName. No need to retrieve Tenant and
* ApplicationProperty
*
* #param value
*/
public TenantApplicationProperty(String value) {
setTenant(null);
setApplicationProperty(null);
setValue(value);
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public ApplicationProperty getApplicationProperty() {
return applicationProperty;
}
public void setApplicationProperty(ApplicationProperty applicationProperty) {
this.applicationProperty = applicationProperty;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
return result;
}
#Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
TenantApplicationProperty tenantAppProp = (TenantApplicationProperty) object;
if (applicationProperty == null) {
if (tenantAppProp.applicationProperty != null) {
return false;
}
} else if (!applicationProperty.getApplicationPropertyGroup().getName().equals(tenantAppProp.applicationProperty.getApplicationPropertyGroup().getName())
|| !applicationProperty.getName().equals(tenantAppProp.applicationProperty.getName())) {
return false;
}
return true;
}
}
TenanatApplicationPropertyPK.java
package com.infor.ecom.tenant.manager.model.entity.pk;
public class TenantApplicationPropertyPK implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String tenant;
private Integer applicationProperty;
public String getTenantId() {
return tenant;
}
public void setTenantId(String tenant) {
this.tenant = tenant;
}
public Integer getApplicationPropertyId() {
return applicationProperty;
}
public void setApplicationPropertyId(Integer applicationProperty) {
this.applicationProperty = applicationProperty;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TenantApplicationPropertyPK tenantAppPropPK = (TenantApplicationPropertyPK) obj;
if (applicationProperty == null) {
if (tenantAppPropPK.applicationProperty != null) {
return false;
}
} else if (!applicationProperty
.equals(tenantAppPropPK.applicationProperty)) {
return false;
}
if (tenant == null) {
if (tenantAppPropPK.tenant != null) {
return false;
}
} else if (!tenant.equals(tenantAppPropPK.tenant)) {
return false;
}
return true;
}
}
ApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "application_property")
public class ApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String defaultValue;
private boolean isVisible;
private boolean clientVisible;
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean getIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public boolean getClientVisible() {
return clientVisible;
}
public void setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
}
public ApplicationPropertyGroup getApplicationPropertyGroup() {
return applicationPropertyGroup;
}
public void setApplicationPropertyGroup(ApplicationPropertyGroup applicationPropertyGroup) {
this.applicationPropertyGroup = applicationPropertyGroup;
}
public ApplicationPropertyType getApplicationPropertyType() {
return applicationPropertyType;
}
public void setApplicationPropertyType(ApplicationPropertyType applicationPropertyType) {
this.applicationPropertyType = applicationPropertyType;
}
}
ApplicationPropertyGroup.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_group")
public class ApplicationPropertyGroup extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ApplicationPropertyType.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_type")
public class ApplicationPropertyType extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TenantServiceImpl.java
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
private Tenant saveTenantWithLog(Tenant tenant, String reason) {
Tenant updatedTenant = tenantRepository.save(tenant);
TenantLog tenantLog = new TenantLog();
tenantLog.setTenantId(updatedTenant.getId());
tenantLog.setDisplayName(updatedTenant.getDisplayName());
tenantLog.setDescription(updatedTenant.getDescription());
tenantLog.setUrl(updatedTenant.getUrl());
tenantLog.setApiKey(updatedTenant.getApiKey());
tenantLog.setStatus(TenantStatusEnum.valueOf(updatedTenant.getStatus()));
tenantLog.setReason(reason);
tenantLog.setMessage(updatedTenant.getMessage());
tenantLogRepository.save(tenantLog);
return updatedTenant;
}
private void setApplicationPropertiesUpdateValues(List<TenantApplicationProperty> existingTenantAppProps, Tenant tenant) {
List<TenantApplicationProperty> newTenantApplicationProperties = (tenant.getTenantApplicationProperties() != null) ? tenant.getTenantApplicationProperties() : new ArrayList<TenantApplicationProperty>();
if(newTenantApplicationProperties.size() != 0) {
for(TenantApplicationProperty tenantAppProp : newTenantApplicationProperties) {
int index = existingTenantAppProps.indexOf(tenantAppProp);
if (index < 0) {
// throw an error -- tenantAppProp should always exist, right?
} else {
existingTenantAppProps.get(index).setValue(tenantAppProp.getValue());
}
}
tenant.setTenantApplicationProperties(existingTenantAppProps);
}
}
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
private Tenant saveExistingTenant(Tenant tenant) {
tenant.setStatus(TenantStatusEnum.INPROGRESS);
tenant.setMessage(ApiMessageConstants.M_DATABASE_UPDATE_INPROGRESS);
String reason = ApiMessageConstants.R_UPDATE_TENANT;
return saveTenantWithLog(tenant, reason);
}
In application property, you defined 1-1 relation like:
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
While you have not defined the same relation (note it should work bidirectionally i.e. say for e.g. if you as a person related to an employee id, then employee id is related to you as a person well) in individual property ApplicationPropertyGroup and ApplicationPropertyType.
You should add the same 1-1 relation in ApplicationPropertyGroup and ApplicationPropertyType with ApplicationProperty.