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.
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 have two Classes, Fount and Criterions, the first one is one to many and the other many to one. When i call delete i get the error mentioned in the title.
I tried a lot of solutions here in stackoverflow and other sites about the same problem, but i can't do it right, i'll be glad if someone find out
Solutions i tried:
Cascade - as you can see, i'm already using the annotation, and i tried a lot of different annotations that i found in the internet
Remove the object Criterion from the object Fount and then the Fount from the Criterion before deleting the Criterion from the database
Remove from Fount object and updating the database right after it
The error:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails
(mydb.fount_criterion, CONSTRAINT
FK5p3wsropwaokyta6cmy3edvcv FOREIGN KEY (criterions_id) REFERENCES
criterion (id))
my classes Fount and Criterion:
package br.com.engcon.entities;
import javax.persistence.*;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "fount")
//#SequenceGenerator(name="SEQUENCE", sequenceName="fount_id_seq")
public class Fount {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(nullable=false, name="url")
private String url;
#OneToMany(fetch = FetchType.LAZY, targetEntity = Criterion.class)
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
private List<Criterion> criterions;
//
// #OneToMany(fetch = FetchType.LAZY, targetEntity = Text.class, orphanRemoval = true)
// #Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
// private List<Text> texts;
#Column(nullable=false, name="isUsed")
private boolean isUsed = false;
#Column(nullable=false, name="isActive")
private boolean isActive = true;
#Column(nullable=false, name="isDeleted")
private boolean isDeleted = false;
public Fount(String url) throws URISyntaxException {
this.url = url;
this.criterions = new ArrayList<Criterion>();
new URI(url);
}
public Fount(String url, List<Criterion> criterions) {
this.url = url;
this.criterions = criterions != null? criterions : new ArrayList<Criterion>();
}
public Fount() {
this.criterions = new ArrayList<Criterion>();
}
public URI getURI() {
if(!url.isEmpty()) {
try {
return new URI(url);
} catch (URISyntaxException e) {
return null;
}
}
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Criterion> getCriterions() {
return criterions;
}
public void setCriterions(List<Criterion> criterions) {
this.criterions = criterions;
}
public void setUrl(String url) {
this.url = url;
}
public void addCriterions(List<Criterion> criterions){
this.criterions = this.criterions != null? this.criterions : new ArrayList<Criterion>();
this.criterions.addAll(criterions);
}
public void addCriterions(Fount fount) {
this.criterions = criterions != null? criterions : new ArrayList<Criterion>();
for(Criterion criterion : fount.getCriterions()) {
Criterion newCriterion = criterion.clone();
newCriterion.setFount(this);
criterions.add(newCriterion);
}
}
public Criterion addCriterion(Criterion criterion) {
this.criterions = criterions != null? criterions : new ArrayList<Criterion>();
Criterion newCriterion = criterion.clone();
newCriterion.setFount(this);
this.criterions.add(newCriterion);
return criterion;
}
public Criterion addCriterion(String criterionTxt) {
return this.addCriterion(new Criterion(criterionTxt));
}
public String getUrl() {
return this.url;
}
#Override
public String toString() {
return this.getUrl();
}
public boolean isUsed() {
return isUsed;
}
public void setUsed(boolean used) {
isUsed = used;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
}
Criterion:
package br.com.engcon.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
#Entity
#Table(name = "criterion")
//#SequenceGenerator(name="SEQUENCE", sequenceName="criterion_id_seq")
public class Criterion {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne(fetch=FetchType.EAGER)
#OnDelete(action = OnDeleteAction.CASCADE)
#JoinColumn(name="fount_id", nullable=false)
private Fount fount;
#Column(nullable=true, name="word_filter")
private String word;
#Column(nullable=false, name="case_sensitive")
private boolean caseSensitive;
public Criterion() {
// TODO Auto-generated constructor stub
caseSensitive = false;
}
public Criterion(String word) {
this.word = word;
this.caseSensitive = false;
}
public Criterion(String word, boolean caseSensitive) {
this.word = word;
this.caseSensitive = caseSensitive;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return word;
}
#Override
public Criterion clone(){
return new Criterion(this.word, this.caseSensitive);
}
public void setWord(String word) {
this.word = word;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
public Fount getFount() {
return fount;
}
public void setFount(Fount fount) {
this.fount = fount;
}
#Override
public String toString() {
return this.word;
}
}
You need to synchronize both end of the bidirectional association.
If you have only 1 bidirectional association (in your example - Criterion-Fount and Fount-Criterion), the following helper methods (for disassociating the parent from all child entities) would solve the problem:
public void addCriterion(Criterion criterion) {
criterions.add(comment);
criterion.setFount(this);
}
public void removeCriterion(Criterion criterion) {
criterions.remove(criterion);
criterion.setFount(null);
}
And make sure you're using cascading:
#OneToMany(mappedBy = "fount", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Criterion> criterions;
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.
I only need to get first name and last name into attribute ownerName and for me the best solution would be if I just call the setter for ownerName in setter of conversationOwner but with this I am getting error:
Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Exception occurred inside setter of medictonproject.model.ConversationEntity.conversationOwner
Here is the Entity class:
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "conversation", schema = "swprojekt")
public class ConversationEntity {
private int conversationId;
private String title;
private Timestamp beginningDate;
#JsonIgnore
private UserEntity conversationOwner;
private String ownerName;
#JsonIgnore
private List<MessageEntity> messages = new ArrayList<>();
private MessageEntity firstMessage;
private boolean seen;
#Transient
public MessageEntity getFirstMessage() {
return firstMessage;
}
public void setFirstMessage(MessageEntity firstMessage) {
this.firstMessage = firstMessage;
}
#Transient
public boolean isSeen() {
return seen;
}
public void setSeen( boolean seen ) {
this.seen = seen;
}
#OneToMany(mappedBy="conversation", cascade = javax.persistence.CascadeType.ALL)
public List<MessageEntity> getMessages() {
return messages;
}
public void setMessages(List<MessageEntity> messages) {
this.messages = messages;
}
#ManyToOne(fetch=FetchType.LAZY, cascade = javax.persistence.CascadeType.ALL)
#JoinColumn(name="user_id")
public UserEntity getConversationOwner() {
return conversationOwner;
}
public void setConversationOwner(UserEntity conversationOwner) {
this.conversationOwner = conversationOwner;
setOwnerName();
}
#Transient
public String getOwnerName() {
return ownerName;
}
public void setOwnerName() {
this.ownerName = conversationOwner.getFirstName() + " " + conversationOwner.getLastName();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "conversation_id", nullable = false)
public int getConversationId() {
return conversationId;
}
public void setConversationId(int conversationId) {
this.conversationId = conversationId;
}
#Basic
#Column(name = "title", nullable = false, length = 200)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Basic
#Column(name = "beginning_date", nullable = false)
public Timestamp getBeginningDate() {
return beginningDate;
}
public void setBeginningDate(Timestamp beginningDate) {
this.beginningDate = beginningDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConversationEntity that = (ConversationEntity) o;
if (conversationId != that.conversationId) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
if (beginningDate != null ? !beginningDate.equals(that.beginningDate) : that.beginningDate != null)
return false;
return true;
}
#Override
public int hashCode() {
int result = conversationId;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (beginningDate != null ? beginningDate.hashCode() : 0);
return result;
}
}
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