I'm using netbeans and generate entity class from database. All of my merge calls to insert and update entities are working perfectly, but when I try to remove an entity, it doesn't delete it from the database, and no exception is thrown. Can someone help me solved. My code below:
AbstractFacade.java
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
AccountEntity.java
#Entity
#Table(name = "Account")
public class AccountEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "account_id")
private Long accountId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_user", nullable = false, length = 100)
private String accountUser;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_pass", nullable = false, length = 100)
private String accountPass;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_fullname", nullable = false, length = 100)
private String accountFullName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_email", nullable = false, length = 100)
private String accountEmail;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_phone", nullable = true, length = 100)
private String accountPhone;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_address", nullable = true, length = 100)
private String accountAddress;
#JoinColumn(name = "role_id", referencedColumnName = "role_id")
#ManyToOne(optional = false)
private RoleEntity roleId;
#JoinColumn(name = "dealer_id", referencedColumnName = "dealer_id")
#ManyToOne(optional = false)
private DealerEntity dealerId;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean available;
public AccountEntity() {
}
public AccountEntity(Long accountId) {
this.accountId = accountId;
}
public AccountEntity(Long accountId, String accountUser, String accountPass) {
this.accountId = accountId;
this.accountUser = accountUser;
this.accountPass = accountPass;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public String getAccountUser() {
return accountUser;
}
public void setAccountUser(String accountUser) {
this.accountUser = accountUser;
}
public String getAccountPass() {
return accountPass;
}
public void setAccountPass(String accountPass) {
this.accountPass = accountPass;
}
public String getAccountFullName() {
return accountFullName;
}
public void setAccountFullName(String accountFullName) {
this.accountFullName = accountFullName;
}
public String getAccountEmail() {
return accountEmail;
}
public void setAccountEmail(String accountEmail) {
this.accountEmail = accountEmail;
}
public String getAccountPhone() {
return accountPhone;
}
public void setAccountPhone(String accountPhone) {
this.accountPhone = accountPhone;
}
public String getAccountAddress() {
return accountAddress;
}
public void setAccountAddress(String accountAddress) {
this.accountAddress = accountAddress;
}
public RoleEntity getRoleId() {
return roleId;
}
public void setRoleId(RoleEntity roleId) {
this.roleId = roleId;
}
public DealerEntity getDealerId() {
return dealerId;
}
public void setDealerId(DealerEntity dealerId) {
this.dealerId = dealerId;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public int hashCode() {
int hash = 0;
hash += (accountId != null ? accountId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof AccountEntity)) {
return false;
}
AccountEntity other = (AccountEntity) object;
if ((this.accountId == null && other.accountId != null) || (this.accountId != null && !this.accountId.equals(other.accountId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.AccountEntity[ accountId=" + accountId + " ]";
}
}
DealerEntity.java
#Entity
#Table(name = "Dealer")
public class DealerEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "dealer_id")
private Long dealerId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "dealer_name", nullable = false, length = 100)
private String dealerName;
#Size(max = 100)
#Column(name = "dealer_phone", length = 100)
private String dealerPhone;
#Size(max = 100)
#Column(name = "dealer_fax", length = 100)
private String dealerFax;
#Size(max = 100)
#Column(name = "dealer_address", length = 100)
private String dealerAddress;
#Size(max = 100)
#Column(name = "dealer_coordinate", length = 100)
private String dealerCoordinate;
#Size(max = 100)
#Column(name = "state_name", length = 100)
private String stateName;
#Basic(optional = false)
#NotNull
#Column(name = "isRoot", nullable = false)
private boolean isRoot;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean isAvailable;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<CustomerEntity> customerEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<ServiceEntity> serviceEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<AccountEntity> accountEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<PurchaseOrderEntity> purchaseOrderEntityList;
#JoinColumn(name = "country_id", referencedColumnName = "country_id", nullable = false)
#ManyToOne(optional = false)
private CountryEntity countryId;
public DealerEntity() {
}
public DealerEntity(Long dealerId) {
this.dealerId = dealerId;
}
public DealerEntity(Long dealerId, String dealerName, boolean isRoot, boolean isAvailable) {
this.dealerId = dealerId;
this.dealerName = dealerName;
this.isRoot = isRoot;
this.isAvailable = isAvailable;
}
public Long getDealerId() {
return dealerId;
}
public void setDealerId(Long dealerId) {
this.dealerId = dealerId;
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public String getDealerPhone() {
return dealerPhone;
}
public void setDealerPhone(String dealerPhone) {
this.dealerPhone = dealerPhone;
}
public String getDealerFax() {
return dealerFax;
}
public void setDealerFax(String dealerFax) {
this.dealerFax = dealerFax;
}
public String getDealerAddress() {
return dealerAddress;
}
public void setDealerAddress(String dealerAddress) {
this.dealerAddress = dealerAddress;
}
public String getDealerCoordinate() {
return dealerCoordinate;
}
public void setDealerCoordinate(String dealerCoordinate) {
this.dealerCoordinate = dealerCoordinate;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public boolean getIsRoot() {
return isRoot;
}
public void setIsRoot(boolean isRoot) {
this.isRoot = isRoot;
}
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
#XmlTransient
public List<CustomerEntity> getCustomerEntityList() {
return customerEntityList;
}
public void setCustomerEntityList(List<CustomerEntity> customerEntityList) {
this.customerEntityList = customerEntityList;
}
#XmlTransient
public List<ServiceEntity> getServiceEntityList() {
return serviceEntityList;
}
public void setServiceEntityList(List<ServiceEntity> serviceEntityList) {
this.serviceEntityList = serviceEntityList;
}
#XmlTransient
public List<AccountEntity> getAccountEntityList() {
return accountEntityList;
}
public void setAccountEntityList(List<AccountEntity> accountEntityList) {
this.accountEntityList = accountEntityList;
}
#XmlTransient
public List<PurchaseOrderEntity> getPurchaseOrderEntityList() {
return purchaseOrderEntityList;
}
public void setPurchaseOrderEntityList(List<PurchaseOrderEntity> purchaseOrderEntityList) {
this.purchaseOrderEntityList = purchaseOrderEntityList;
}
public CountryEntity getCountryId() {
return countryId;
}
public void setCountryId(CountryEntity countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (dealerId != null ? dealerId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DealerEntity)) {
return false;
}
DealerEntity other = (DealerEntity) object;
if ((this.dealerId == null && other.dealerId != null) || (this.dealerId != null && !this.dealerId.equals(other.dealerId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.DealerEntity[ dealerId=" + dealerId + " ]";
}
}
It would appear that your persistence context is not in synch with the underlying database.
Try the following:
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
getEntityManager().flush();
}
Related
I've created ManyToMany tables with extra column that's named reqserviceguest_details, then I've tested with filling on my jsp page form to insert the data. When the all data inserted, everything is fine except my servicelaundry_id. It's null and I have no idea why it happened.
ReqServiceGuestDetails.class
#Entity
#Table(name = "reqserviceguest_details")
public class ReqServiceGuestDetails {
#Id
#Column(name = "reqserviceguest_details_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
#ManyToOne
#JoinColumn(name = "reqserviceguest_id")
private ReqServiceGuest reqServiceGuest;
#ManyToOne
#JoinColumn(name = "servicelaundry_id")
private ServiceLaundry serviceLaundry;
private int amount;
public ReqServiceGuestDetails() {
}
public ReqServiceGuestDetails(ReqServiceGuest reqServiceGuest, ServiceLaundry serviceLaundry, int amount) {
this.reqServiceGuest = reqServiceGuest;
this.serviceLaundry = serviceLaundry;
this.amount = amount;
}
public ReqServiceGuest getReqServiceGuest() {
return reqServiceGuest;
}
public void setReqServiceGuest(ReqServiceGuest reqServiceGuest) {
this.reqServiceGuest = reqServiceGuest;
}
public ServiceLaundry getServiceLaundry() {
return serviceLaundry;
}
public void setServiceLaundry(ServiceLaundry serviceLaundry) {
this.serviceLaundry = serviceLaundry;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
ReqServiceGuest.class
#Entity
#Table(name = "reqserviceguest")
public class ReqServiceGuest {
#Id
#Column(name = "reqserviceguest_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String reqServiceGuestId;
private Date reqDate;
private Date pickDate;
private String type;
private String serviceStatus;
private String guestName;
private String guestTelNo;
#OneToMany(mappedBy = "reqServiceGuest", cascade = CascadeType.ALL)
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReqServiceGuestId() {
return reqServiceGuestId;
}
public void setReqServiceGuestId(String reqServiceGuestId) {
this.reqServiceGuestId = reqServiceGuestId;
}
public Date getReqDate() {
return reqDate;
}
public void setReqDate(Date reqDate) {
this.reqDate = reqDate;
}
public Date getPickDate() {
return pickDate;
}
public void setPickDate(Date pickDate) {
this.pickDate = pickDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getGuestName() {
return guestName;
}
public void setGuestName(String guestName) {
this.guestName = guestName;
}
public String getGuestTelNo() {
return guestTelNo;
}
public void setGuestTelNo(String guestTelNo) {
this.guestTelNo = guestTelNo;
}
public Set<ReqServiceGuestDetails> getReqServiceGuestDetails() {
return reqServiceGuestDetails;
}
public void setReqServiceGuestDetails(Set<ReqServiceGuestDetails> reqServiceGuestDetails) {
this.reqServiceGuestDetails = reqServiceGuestDetails;
}
}
ServiceLaundry.class
#Entity
#Table(name = "servicelaundry")
public class ServiceLaundry {
#Id
#Column(name = "servicelaundry_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String serviceId;
private String serviceName;
private int price;
#OneToMany(mappedBy = "serviceLaundry")
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And this is form processor in a controller
#RequestMapping(path = "/savereqserviceguest", method = RequestMethod.GET)
public String processAddReqServiceGuestForm (ReqServiceGuest reqServiceGuest, #RequestParam Map<String, String> allParams) {
int latestId = reqServiceGuestService.getLatestReqServiceGuestId();
reqServiceGuest.setReqServiceGuestId(generateReqServiceGuestId(latestId));
reqServiceGuest.setServiceStatus("NP");
/*
for (Map.Entry<String, String> entry : allParams.entrySet()) {
if (entry.getKey().contains("service")) {
String getServiceId = String.valueOf(entry.getKey().charAt(7));
reqServiceGuest.getReqServiceGuestServiceLaundry().add();
}
}
reqServiceGuest.setReqServiceGuestServiceLaundry(serviceGuestDetails);
*/
ServiceLaundry service1 = serviceLaundryService.getServiceLaundry(1);
ServiceLaundry service2 = serviceLaundryService.getServiceLaundry(2);
ReqServiceGuestDetails reqServiceGuestDetails1 = new ReqServiceGuestDetails(reqServiceGuest, service1, 55);
ReqServiceGuestDetails reqServiceGuestDetails2 = new ReqServiceGuestDetails(reqServiceGuest, service2, 35);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails1);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails2);
Calendar cReqDate = Calendar.getInstance();
if (reqServiceGuest.getType().equals("Ordinary")) {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 5);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
} else {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 2);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
}
reqServiceGuestService.saveReqServiceGuest(reqServiceGuest);
return "redirect:/home";
}
And the final result is
Result
I am using Spring Boot 2.7.2 , Java/JDK 18.
Entity
#Entity
#Table(name = "account")
public class Account {
#EmbeddedId
private AccountId id;
#MapsId("tenantId")
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "tenant_id", nullable = false)
private Tenant tenant;
#Column(name = "account_number", nullable = false, length = 32)
private String accountNumber;
#Column(name = "account_name", nullable = false, length = 128)
private String accountName;
#Column(name = "account_name_english", length = 128)
private String accountNameEnglish;
#Column(name = "account_name_chinese", length = 128)
private String accountNameChinese;
#Column(name = "account_name_korean", length = 128)
private String accountNameKorean;
#Column(name = "description", length = 512)
private String description;
#Column(name = "parent_id")
private Integer parentId;
#Column(name = "bkit_code_id", length = 128)
private String bkitCodeId;
#Column(name = "grade")
private Integer grade;
#Column(name = "is_parent", nullable = false)
private Boolean isParent = false;
#Column(name = "account_category_kind", nullable = false)
private Integer accountCategoryKind;
#Column(name = "is_postable_in_foreign_currency", nullable = false)
private Boolean isPostableInForeignCurrency = false;
#Column(name = "detail_by_account_object", nullable = false)
private Boolean detailByAccountObject = false;
#Column(name = "account_object_type")
private Integer accountObjectType;
#Column(name = "detail_by_bank_account", nullable = false)
private Boolean detailByBankAccount = false;
#Column(name = "detail_by_job", nullable = false)
private Boolean detailByJob = false;
#Column(name = "detail_by_job_kind")
private Integer detailByJobKind;
#Column(name = "detail_by_project_work", nullable = false)
private Boolean detailByProjectWork = false;
#Column(name = "detail_by_project_work_kind")
private Integer detailByProjectWorkKind;
#Column(name = "detail_by_order", nullable = false)
private Boolean detailByOrder = false;
#Column(name = "detail_by_order_kind")
private Integer detailByOrderKind;
#Column(name = "detail_by_contract", nullable = false)
private Boolean detailByContract = false;
#Column(name = "detail_by_contract_kind")
private Integer detailByContractKind;
#Column(name = "detail_by_expense_item", nullable = false)
private Boolean detailByExpenseItem = false;
#Column(name = "detail_by_expense_item_kind")
private Integer detailByExpenseItemKind;
#Column(name = "detail_by_department", nullable = false)
private Boolean detailByDepartment = false;
#Column(name = "detail_by_department_kind")
private Integer detailByDepartmentKind;
#Column(name = "detail_by_list_item", nullable = false)
private Boolean detailByListItem = false;
#Column(name = "detail_by_list_item_kind")
private Integer detailByListItemKind;
#Column(name = "active_status", nullable = false)
private Boolean activeStatus = false;
#Column(name = "created")
private OffsetDateTime created;
#Column(name = "created_by", length = 64)
private String createdBy;
#Column(name = "modified")
private OffsetDateTime modified;
#Column(name = "modified_by", length = 64)
private String modifiedBy;
#Column(name = "sort_bkit_code_id", length = 128)
private String sortBkitCodeId;
#Column(name = "detail_by_pu_contract", nullable = false)
private Boolean detailByPuContract = false;
#Column(name = "detail_by_pu_contract_kind")
private Integer detailByPuContractKind;
public AccountId getId() {
return id;
}
public void setId(AccountId id) {
this.id = id;
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountNameEnglish() {
return accountNameEnglish;
}
public void setAccountNameEnglish(String accountNameEnglish) {
this.accountNameEnglish = accountNameEnglish;
}
public String getAccountNameChinese() {
return accountNameChinese;
}
public void setAccountNameChinese(String accountNameChinese) {
this.accountNameChinese = accountNameChinese;
}
public String getAccountNameKorean() {
return accountNameKorean;
}
public void setAccountNameKorean(String accountNameKorean) {
this.accountNameKorean = accountNameKorean;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getBkitCodeId() {
return bkitCodeId;
}
public void setBkitCodeId(String bkitCodeId) {
this.bkitCodeId = bkitCodeId;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Boolean getIsParent() {
return isParent;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
public Integer getAccountCategoryKind() {
return accountCategoryKind;
}
public void setAccountCategoryKind(Integer accountCategoryKind) {
this.accountCategoryKind = accountCategoryKind;
}
public Boolean getIsPostableInForeignCurrency() {
return isPostableInForeignCurrency;
}
public void setIsPostableInForeignCurrency(Boolean isPostableInForeignCurrency) {
this.isPostableInForeignCurrency = isPostableInForeignCurrency;
}
public Boolean getDetailByAccountObject() {
return detailByAccountObject;
}
public void setDetailByAccountObject(Boolean detailByAccountObject) {
this.detailByAccountObject = detailByAccountObject;
}
public Integer getAccountObjectType() {
return accountObjectType;
}
public void setAccountObjectType(Integer accountObjectType) {
this.accountObjectType = accountObjectType;
}
public Boolean getDetailByBankAccount() {
return detailByBankAccount;
}
public void setDetailByBankAccount(Boolean detailByBankAccount) {
this.detailByBankAccount = detailByBankAccount;
}
public Boolean getDetailByJob() {
return detailByJob;
}
public void setDetailByJob(Boolean detailByJob) {
this.detailByJob = detailByJob;
}
public Integer getDetailByJobKind() {
return detailByJobKind;
}
public void setDetailByJobKind(Integer detailByJobKind) {
this.detailByJobKind = detailByJobKind;
}
public Boolean getDetailByProjectWork() {
return detailByProjectWork;
}
public void setDetailByProjectWork(Boolean detailByProjectWork) {
this.detailByProjectWork = detailByProjectWork;
}
public Integer getDetailByProjectWorkKind() {
return detailByProjectWorkKind;
}
public void setDetailByProjectWorkKind(Integer detailByProjectWorkKind) {
this.detailByProjectWorkKind = detailByProjectWorkKind;
}
public Boolean getDetailByOrder() {
return detailByOrder;
}
public void setDetailByOrder(Boolean detailByOrder) {
this.detailByOrder = detailByOrder;
}
public Integer getDetailByOrderKind() {
return detailByOrderKind;
}
public void setDetailByOrderKind(Integer detailByOrderKind) {
this.detailByOrderKind = detailByOrderKind;
}
public Boolean getDetailByContract() {
return detailByContract;
}
public void setDetailByContract(Boolean detailByContract) {
this.detailByContract = detailByContract;
}
public Integer getDetailByContractKind() {
return detailByContractKind;
}
public void setDetailByContractKind(Integer detailByContractKind) {
this.detailByContractKind = detailByContractKind;
}
public Boolean getDetailByExpenseItem() {
return detailByExpenseItem;
}
public void setDetailByExpenseItem(Boolean detailByExpenseItem) {
this.detailByExpenseItem = detailByExpenseItem;
}
public Integer getDetailByExpenseItemKind() {
return detailByExpenseItemKind;
}
public void setDetailByExpenseItemKind(Integer detailByExpenseItemKind) {
this.detailByExpenseItemKind = detailByExpenseItemKind;
}
public Boolean getDetailByDepartment() {
return detailByDepartment;
}
public void setDetailByDepartment(Boolean detailByDepartment) {
this.detailByDepartment = detailByDepartment;
}
public Integer getDetailByDepartmentKind() {
return detailByDepartmentKind;
}
public void setDetailByDepartmentKind(Integer detailByDepartmentKind) {
this.detailByDepartmentKind = detailByDepartmentKind;
}
public Boolean getDetailByListItem() {
return detailByListItem;
}
public void setDetailByListItem(Boolean detailByListItem) {
this.detailByListItem = detailByListItem;
}
public Integer getDetailByListItemKind() {
return detailByListItemKind;
}
public void setDetailByListItemKind(Integer detailByListItemKind) {
this.detailByListItemKind = detailByListItemKind;
}
public Boolean getActiveStatus() {
return activeStatus;
}
public void setActiveStatus(Boolean activeStatus) {
this.activeStatus = activeStatus;
}
public OffsetDateTime getCreated() {
return created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public OffsetDateTime getModified() {
return modified;
}
public void setModified(OffsetDateTime modified) {
this.modified = modified;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public String getSortBkitCodeId() {
return sortBkitCodeId;
}
public void setSortBkitCodeId(String sortBkitCodeId) {
this.sortBkitCodeId = sortBkitCodeId;
}
public Boolean getDetailByPuContract() {
return detailByPuContract;
}
public void setDetailByPuContract(Boolean detailByPuContract) {
this.detailByPuContract = detailByPuContract;
}
public Integer getDetailByPuContractKind() {
return detailByPuContractKind;
}
public void setDetailByPuContractKind(Integer detailByPuContractKind) {
this.detailByPuContractKind = detailByPuContractKind;
}
}
#Embeddable
public class AccountId implements Serializable {
private static final long serialVersionUID = 2728412978200770912L;
#Column(name = "id", nullable = false)
private Integer id;
#Column(name = "tenant_id", nullable = false)
private Integer tenantId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTenantId() {
return tenantId;
}
public void setTenantId(Integer tenantId) {
this.tenantId = tenantId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
AccountId entity = (AccountId) o;
return Objects.equals(this.tenantId, entity.tenantId) &&
Objects.equals(this.id, entity.id);
}
#Override
public int hashCode() {
return Objects.hash(tenantId, id);
}
}
My services
public interface AccountService {
// FIXME: Need get Account belong to tenant_id .
List<Account> getAll();
}
and
#Service
public class AccountServiceImpl implements AccountService {
#Autowired
AccountRepository accountRepository;
// FIXME: Need get Account belong to tenant_id .
#Override
public List<Account> getAll() {
return accountRepository.findAll(); // <-- Need revise.
}
}
How to find all accounts by a tenant_id? I can use native SQL query, but I want use Spring Data JPA API more than.
You can use Spring Data Repository query keywords on your composite key by find all accounts by following code.
#Repository
public interface AccountRepository extends JpaRepository<Account, AccountId> {
List<Account> findAllByTenantId(Integer tenant_id);
}
So I was trying to insert a boarding pass item (BoardingPassSessionBean) into a database and it came out with this exception. I did try to figure out what was wrong but I am so confused. I didn't even set the boarding pass id to have ticket flight in the (BoardingPassSessionBean) but somehow the Exceptions show cant set flight id to ticketflight. Any help or advice would be greatly appreciated. Through debug mode i know that the exception happen while persisting the item
TicketFlight
#Entity
#Table(name = "ticket_flights", schema = "bookings")
public class TicketFlight {
#EmbeddedId
private TicketFlightId id;
#MapsId("flightId")
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinColumn(name = "flight_id")
private Flight flight;
#Column(name = "fare_conditions", nullable = false, length = 10)
private String fareConditions;
#Column(name = "amount", nullable = false, precision = 10, scale = 2)
private BigDecimal amount;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "ticketFlights", cascade = { CascadeType.MERGE, CascadeType.REMOVE })
private BoardingPass boardingPasses;
#MapsId("ticketNo")
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
#JoinColumn(name = "ticket_no")
private Ticket ticket;
public TicketFlight() {}
public TicketFlight(TicketFlightId id) {
this.id = id;
}
public Ticket getTicket() {
return ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
public BoardingPass getBoardingPasses() {
return boardingPasses;
}
public void setBoardingPasses(BoardingPass boardingPasses) {
this.boardingPasses = boardingPasses;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getFareConditions() {
return fareConditions;
}
public void setFareConditions(String fareConditions) {
this.fareConditions = fareConditions;
}
public Flight getFlight() {
return flight;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public TicketFlightId getId() {
return id;
}
public void setId(TicketFlightId id) {
this.id = id;
}
}
BoardingPassSessionBean
#Stateless
public class BoardingPassSessionBean implements BoardingPassSessionBeanLocal{
#PersistenceContext(unitName = "flightApp")
EntityManager em;
#Override
public void addBoardingPass(TicketDTO ticketDTO, TicketFlight ticketFlight) throws EJBException {
BoardingPass boardingPass = new BoardingPass();
setBoardingPassDetail(boardingPass, ticketFlight, ticketDTO);
em.persist(boardingPass);
}
private void setBoardingPassDetail(BoardingPass boardingPass, TicketFlight ticketFlight, TicketDTO ticketDTO) {
Random rand = new Random();
boardingPass.setBoardingNo(rand.nextInt());
boardingPass.setId(new BoardingPassId(ticketFlight.getId().getTicketNo(), ticketFlight.getId().getFlightId()));
boardingPass.setSeatNo(ticketDTO.getSeatNo());
boardingPass.setTicketFlights(ticketFlight);
}
}
BoardingPass
#Entity
#Table(name = "boarding_passes", schema = "bookings")
public class BoardingPass {
#EmbeddedId
private BoardingPassId id;
#MapsId
#OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.REMOVE)
#JoinColumns({
#JoinColumn(name = "ticket_no", referencedColumnName = "ticket_no", nullable = false),
#JoinColumn(name = "flight_id", referencedColumnName = "flight_id", nullable = false)
})
private TicketFlight ticketFlights;
#Column(name = "boarding_no", nullable = false)
private Integer boardingNo;
#Column(name = "seat_no", nullable = false, length = 4)
private String seatNo;
public BoardingPass() {}
public String getSeatNo() {
return seatNo;
}
public void setSeatNo(String seatNo) {
this.seatNo = seatNo;
}
public Integer getBoardingNo() {
return boardingNo;
}
public void setBoardingNo(Integer boardingNo) {
this.boardingNo = boardingNo;
}
public TicketFlight getTicketFlights() {
return ticketFlights;
}
public void setTicketFlights(TicketFlight ticketFlights) {
this.ticketFlights = ticketFlights;
}
public BoardingPassId getId() {
return id;
}
public void setId(BoardingPassId id) {
this.id = id;
}
}
BoardingPassId
#Embeddable
public class BoardingPassId implements Serializable {
private static final long serialVersionUID = -4075241131735714893L;
#Column(name = "ticket_no", nullable = false, length = 13)
private String ticketNo;
#Column(name = "flight_id", nullable = false)
private Integer flightId;
public BoardingPassId() {}
public Integer getFlightId() {
return flightId;
}
public void setFlightId(Integer flightId) {
this.flightId = flightId;
}
public String getTicketNo() {
return ticketNo;
}
public void setTicketNo(String ticketNo) {
this.ticketNo = ticketNo;
}
#Override
public int hashCode() {
return Objects.hash(ticketNo, flightId);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
BoardingPassId entity = (BoardingPassId) o;
return Objects.equals(this.ticketNo, entity.ticketNo) &&
Objects.equals(this.flightId, entity.flightId);
}
public BoardingPassId(String ticketNo, Integer flightId) {
this.ticketNo = ticketNo;
this.flightId = flightId;
}
}
I have a (inneficient, but working) T-SQL (sub)query
SELECT * FROM DIAGE.ade.UorPos WHERE Prefixo IN
(SELECT PrefixoJurisdicionada FROM DIAGE.ade.Jurisdicionadas WHERE Prefixo =
(SELECT Prefixo FROM DIAGE.ade.Jurisdicionadas WHERE PrefixoJurisdicionada = 8922))
AND CodComissao IN (4345, 4346, 4347)
which I've build the correspondent JPQL
SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada = :prefixo))
AND u.codComissao IN (4345, 4346, 4347)
Despite compiling, when running launches the Exception:
[...]
Caused by: Exception [EclipseLink-6069] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: The field [DIAGE.ade.Prefixos.Prefixo] in this
expression has an invalid table in this context.
Query: ReadAllQuery(name="UorPos.findUorPosExecutivosByPrefixo"
referenceClass=UorPos jpql="SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada =
:prefixo)) AND u.codComissao IN (4345, 4346, 4347)") at
org.eclipse.persistence.exceptions.QueryException. invalidTableForFieldInExpression (QueryException.java:749)
at org.eclipse.persistence.internal.expressions.FieldExpression.validateNode(FieldExpression.java:296)
at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3275)
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369)
at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:223)
I've made some research and, in my understanding, my JPQL query is ok.
Can anyone help me to resolve this?
Some links I've researched:
item 2.5.15
How do I do a JPQL SubQuery?
item 5
item 10.2.5.15
Using IN with a subquery
I'm using EclipseLink version 2.5.2 (integrated with Netbeans 8.0.2), Glassfish 4.1, Java 1.7.0_71.
UPDATED
The UorPos entity:
#Entity
#Table(name = "UorPos", catalog = "DIAGE", schema = "ade")
#XmlRootElement
#NamedQueries({
#NamedQuery(name="UorPos.findXByY", query="SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada = :prefixo))
AND u.codComissao IN (4345, 4346, 4347)")
})
public class UorPos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 8)
#Column(name = "Matricula")
private String matricula;
#Size(max = 200)
#Column(name = "Nome")
private String nome;
#Size(max = 200)
#Column(name = "NomeGuerra")
private String nomeGuerra;
#Column(name = "CodComissao")
private Integer codComissao;
#Size(max = 25)
#Column(name = "NomeComissao")
private String nomeComissao;
#Size(max = 4)
#Column(name = "CodNivel")
private String codNivel;
#Size(max = 50)
#Column(name = "DescNivel")
private String descNivel;
#Size(max = 50)
#Column(name = "eMailFuncionario")
private String eMailFuncionario;
#Column(name = "DataCaptura")
#Temporal(TemporalType.TIMESTAMP)
private Date dataCaptura;
#Column(name = "DataPermissaoAcesso")
#Temporal(TemporalType.TIMESTAMP)
private Date dataPermissaoAcesso;
#ManyToMany(mappedBy = "uorPosCollection")
private Collection<Demandas> demandasCollection;
#ManyToMany(mappedBy = "uorPosCollection1")
private Collection<Demandas> demandasCollection1;
#ManyToMany(mappedBy = "uorPosCollection2")
private Collection<Demandas> demandasCollection2;
#JoinColumn(name = "UORpos", referencedColumnName = "UORpos")
#ManyToOne(optional = false)
private Divisoes uORpos;
#JoinColumn(name = "idPermissaoAcesso", referencedColumnName = "idPermissaoAcesso")
#ManyToOne
private PermissoesAcesso idPermissaoAcesso;
#JoinColumn(name = "Prefixo", referencedColumnName = "Prefixo")
#ManyToOne
private Prefixos prefixo;
#OneToMany(mappedBy = "matricula")
private Collection<Anotacoes> anotacoesCollection;
#OneToMany(mappedBy = "matricula")
private Collection<Log> logCollection;
public UorPos() {
}
public UorPos(String matricula) {
this.matricula = matricula;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNomeGuerra() {
return nomeGuerra;
}
public void setNomeGuerra(String nomeGuerra) {
this.nomeGuerra = nomeGuerra;
}
public Integer getCodComissao() {
return codComissao;
}
public void setCodComissao(Integer codComissao) {
this.codComissao = codComissao;
}
public String getNomeComissao() {
return nomeComissao;
}
public void setNomeComissao(String nomeComissao) {
this.nomeComissao = nomeComissao;
}
public String getCodNivel() {
return codNivel;
}
public void setCodNivel(String codNivel) {
this.codNivel = codNivel;
}
public String getDescNivel() {
return descNivel;
}
public void setDescNivel(String descNivel) {
this.descNivel = descNivel;
}
public String getEMailFuncionario() {
return eMailFuncionario;
}
public void setEMailFuncionario(String eMailFuncionario) {
this.eMailFuncionario = eMailFuncionario;
}
public Date getDataCaptura() {
return dataCaptura;
}
public void setDataCaptura(Date dataCaptura) {
this.dataCaptura = dataCaptura;
}
public Date getDataPermissaoAcesso() {
return dataPermissaoAcesso;
}
public void setDataPermissaoAcesso(Date dataPermissaoAcesso) {
this.dataPermissaoAcesso = dataPermissaoAcesso;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection() {
return demandasCollection;
}
public void setDemandasCollection(Collection<Demandas> demandasCollection) {
this.demandasCollection = demandasCollection;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection1() {
return demandasCollection1;
}
public void setDemandasCollection1(Collection<Demandas> demandasCollection1) {
this.demandasCollection1 = demandasCollection1;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection2() {
return demandasCollection2;
}
public void setDemandasCollection2(Collection<Demandas> demandasCollection2) {
this.demandasCollection2 = demandasCollection2;
}
public Divisoes getUORpos() {
return uORpos;
}
public void setUORpos(Divisoes uORpos) {
this.uORpos = uORpos;
}
public PermissoesAcesso getIdPermissaoAcesso() {
return idPermissaoAcesso;
}
public void setIdPermissaoAcesso(PermissoesAcesso idPermissaoAcesso) {
this.idPermissaoAcesso = idPermissaoAcesso;
}
public Prefixos getPrefixo() {
return prefixo;
}
public void setPrefixo(Prefixos prefixo) {
this.prefixo = prefixo;
}
#XmlTransient
public Collection<Anotacoes> getAnotacoesCollection() {
return anotacoesCollection;
}
public void setAnotacoesCollection(Collection<Anotacoes> anotacoesCollection) {
this.anotacoesCollection = anotacoesCollection;
}
#XmlTransient
public Collection<Log> getLogCollection() {
return logCollection;
}
public void setLogCollection(Collection<Log> logCollection) {
this.logCollection = logCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (matricula != null ? matricula.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof UorPos)) {
return false;
}
UorPos other = (UorPos) object;
if ((this.matricula == null && other.matricula != null) || (this.matricula != null && !this.matricula.equals(other.matricula))) {
return false;
}
return true;
}
#Override
public String toString() {
return "br.com.bb.uop.dcvipat.ade.entity.UorPos[ matricula=" + matricula + " ]";
}
}
The Jurisdicionadas entity:
#Entity
#Table(name = "Jurisdicionadas", catalog = "DIAGE", schema = "ade")
#XmlRootElement
#NamedQueries({
#NamedQuery(name="Jurisdicionadas.findAll", query="SELECT j FROM Jurisdicionadas j")})
public class Jurisdicionadas implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "PrefixoJurisdicionada")
private Integer prefixoJurisdicionada;
#Size(max = 200)
#Column(name = "NomePrefixoJurisdicionada")
private String nomePrefixoJurisdicionada;
#JoinColumn(name = "Prefixo", referencedColumnName = "Prefixo")
#ManyToOne
private Prefixos prefixo;
public Jurisdicionadas() {
}
public Jurisdicionadas(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPrefixoJurisdicionada() {
return prefixoJurisdicionada;
}
public void setPrefixoJurisdicionada(Integer prefixoJurisdicionada) {
this.prefixoJurisdicionada = prefixoJurisdicionada;
}
public String getNomePrefixoJurisdicionada() {
return nomePrefixoJurisdicionada;
}
public void setNomePrefixoJurisdicionada(String nomePrefixoJurisdicionada) {
this.nomePrefixoJurisdicionada = nomePrefixoJurisdicionada;
}
public Prefixos getPrefixo() {
return prefixo;
}
public void setPrefixo(Prefixos prefixo) {
this.prefixo = prefixo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Jurisdicionadas)) {
return false;
}
Jurisdicionadas other = (Jurisdicionadas) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "br.com.bb.uop.dcvipat.ade.entity.Jurisdicionadas[ id=" + id + " ]";
}
}
Thanks in advance.
After the great hint posted by htshame, I've researched about Eclipselink Native SQL Queries and workarounded the problem as below:
public List<UorPos> findUorPosExecutivosByPrefixo(Prefixos prefixo) {
return (List<UorPos>) getEntityManager().createNativeQuery("SELECT * FROM DIAGE.ade.UorPos WHERE prefixo IN (SELECT prefixoJurisdicionada FROM DIAGE.ade.Jurisdicionadas WHERE prefixo = (SELECT prefixo FROM DIAGE.ade.Jurisdicionadas WHERE prefixoJurisdicionada = ?)) AND codComissao IN (4345, 4346, 4347) ORDER BY nome, matricula", UorPos.class).setParameter(1, prefixo.getPrefixo()).getResultList();
}
But, if someone could resolve the JPQL named query issue, it will be better.
STAFF CLASS
#Entity
#Table(name = "staff", catalog = "nibblrdw_collections")
public class Staff implements java.io.Serializable {
private Integer id;
private StafRole stafRole;
private String stfId;
#NotEmpty(message="please enter staff name")
private String stfName;
#NotEmpty(message="please enter staff Username")
#Size(min = 6, max = 15, message = "Lenght must be between 6 to 15 characters")
private String stfUsrName;
#NotEmpty(message="please enter staff password")
#Size(min = 6, max = 10, message = "Lenght must be between 6 to 10 characters")
private String stfUsrPwd;
private boolean stfVisF;
private Date crtTs;
private Date updTs;
private String crtId;
private String updId;
#NotNull(message="please enter Staff Device ID")
private Integer deviceId;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#JsonBackReference
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "stf_role", nullable = false)
public StafRole getStafRole() {
return this.stafRole;
}
public void setStafRole(StafRole stafRole) {
this.stafRole = stafRole;
}
#Column(name = "stf_id", nullable = false)
public String getStfId() {
return this.stfId;
}
public void setStfId(String stfId) {
this.stfId = stfId;
}
#Column(name = "stf_name", nullable = false, length = 65535)
public String getStfName() {
return this.stfName;
}
public void setStfName(String stfName) {
this.stfName = stfName;
}
#Column(name = "stf_usr_name", length = 100)
public String getStfUsrName() {
return this.stfUsrName;
}
public void setStfUsrName(String stfUsrName) {
this.stfUsrName = stfUsrName;
}
#Column(name = "stf_usr_pwd", length = 100)
public String getStfUsrPwd() {
return this.stfUsrPwd;
}
public void setStfUsrPwd(String stfUsrPwd) {
this.stfUsrPwd = stfUsrPwd;
}
#Column(name = "stf_vis_f", nullable = false)
public boolean isStfVisF() {
return this.stfVisF;
}
public void setStfVisF(boolean stfVisF) {
this.stfVisF = stfVisF;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "crt_ts", nullable = false, length = 0)
public Date getCrtTs() {
return this.crtTs;
}
public void setCrtTs(Date crtTs) {
this.crtTs = crtTs;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "upd_ts", nullable = false, length = 0)
public Date getUpdTs() {
return this.updTs;
}
public void setUpdTs(Date updTs) {
this.updTs = updTs;
}
#Column(name = "crt_id", nullable = false, length = 100)
public String getCrtId() {
return this.crtId;
}
public void setCrtId(String crtId) {
this.crtId = crtId;
}
#Column(name = "upd_id", length = 100)
public String getUpdId() {
return this.updId;
}
public void setUpdId(String updId) {
this.updId = updId;
}
#Column(name = "device_id", nullable = false)
public Integer getDeviceId() {
return this.deviceId;
}
public void setDeviceId(Integer deviceId) {
this.deviceId = deviceId;
}
}
StafTyp class
#Entity
#Table(name = "staf_role", catalog = "nibblrdw_collections")
public class StafRole implements java.io.Serializable {
private Integer id;
private String roleDesc;
private String crtId;
private Date crtTs;
private String updId;
private Date updTs;
private Set<Staff> staffs = new HashSet<Staff>(0);
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "role_desc", nullable = false, length = 45)
public String getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
#Column(name = "crt_id", length = 45)
public String getCrtId() {
return this.crtId;
}
public void setCrtId(String crtId) {
this.crtId = crtId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "crt_ts", nullable = false, length = 0)
public Date getCrtTs() {
return this.crtTs;
}
public void setCrtTs(Date crtTs) {
this.crtTs = crtTs;
}
#Column(name = "upd_id", length = 45)
public String getUpdId() {
return this.updId;
}
public void setUpdId(String updId) {
this.updId = updId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "upd_ts", nullable = false, length = 0)
public Date getUpdTs() {
return this.updTs;
}
public void setUpdTs(Date updTs) {
this.updTs = updTs;
}
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "stafRole")
public Set<Staff> getStaffs() {
return this.staffs;
}
public void setStaffs(Set<Staff> staffs) {
this.staffs = staffs;
}
}
CONTROLLER
#RequestMapping(value="loginmob", method = RequestMethod.GET)
public #ResponseBody Object test() {
LoginModel login=new LoginModel();
login.setName("report");
login.setPassword("report123");
JSONObject obj = new JSONObject();
if(!login.getName().isEmpty() & !login.getPassword().isEmpty()){
Staff staff=((StaffHomeService) staffService).login(login.getName(), login.getPassword());
System.out.println(staff.getStfUsrName()+" "+staff.getStfUsrPwd());
//logs exception
if(staff.getStfUsrName()!=null){
StafRole sr=staff.getStafRole();
System.out.println(sr.getRoleDesc());
obj.put("id", staff.getId());
obj.put("stf_name", staff.getStfName());
return staff;
}
}
return obj;
}
JSON OBJECT IN URL
{"id":2,"stfId":"2","stfName":"Admin","stfUsrName":"report","stfUsrPwd":"report123","stfVisF":true,"crtTs":1421048214000,"updTs":1422471300000,"crtId":"admin","updId":"null","deviceId":1}
Here my problem is StafTyp is not serializing in to json object. What changes need to do to get StafTyp object to Json?
You switched JSON annotations on Staff and StaffRole.
Staff#getStafRole() should be annotated with #JsonManagedReference, and StafRole#getStaffs() should be annotated with #JsonBackReference. This way staff -> stafRole will be serialized to JSON, and staff -> staffRole -> staffs won't, which is what you need.