unable to get manytoone mapping object in json, from Spring Hibernate - java

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.

Related

Use Spring Data JPA API: How to get list of Account by tennat_id (belong to a composite primary key)?

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);
}

java.lang.IllegalArgumentException: Can not set java.lang.Integer field model.entity.BoardingPassId.flightId to model.entity.TicketFlightId

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;
}
}

need to save child without retrieve it in hibernate

I need to save the child table values without retrieve the values.
POJO Class:
public class User {
private String firstName;
#Id
#SequenceGenerator(name = "userID", sequenceName = "userID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
#Column(name = "id")
private Long id;
private String lastName;
private Integer passwordReset;
#Column(name = "useremail", nullable = false, unique = true)
#Email
#NotEmpty
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<WashingOrder> orderList;
#Column(unique = true)
#NotEmpty(message = "{username}")
private String username;
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setId(Long id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPasswordReset() {
return passwordReset;
}
public void setPasswordReset(Integer passwordReset) {
this.passwordReset = passwordReset;
}
public List<WashingOrder> getOrderList() {
return orderList;
}
public void setOrderList(List<WashingOrder> orderList) {
this.orderList = orderList;
}
}
public class WashingOrder {
#Id
#SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
#Column(name = "orderNo")
private Long orderNo;
#Column(name = "totalClothes", nullable = false)
#NotNull
private Integer totalClothes;
#Column(name = "mensCloth", nullable = true)
private Integer mensCloth;
#Column(name = "womensCloth", nullable = true)
private Integer womensCloth;
#Column(name = "otherCloth", nullable = true)
private Integer otherClothes;
#Column(name = "deliveryDate", nullable = true)
/* #DateTimeFormat(pattern = "yyyy-mm-dd") */
private Date deliveryDate;
#Column(name = "status", nullable = true)
private String orderStatus;
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getTotalClothes() {
return totalClothes;
}
public void setTotalClothes(Integer totalClothes) {
this.totalClothes = totalClothes;
}
public Integer getMensCloth() {
return mensCloth;
}
public void setMensCloth(Integer mensCloth) {
this.mensCloth = mensCloth;
}
public Integer getWomensCloth() {
return womensCloth;
}
public void setWomensCloth(Integer womensCloth) {
this.womensCloth = womensCloth;
}
public Integer getOtherClothes() {
return otherClothes;
}
public void setOtherClothes(Integer otherClothes) {
this.otherClothes = otherClothes;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
Implementation:
Session session = sessionFactory.getCurrentSession();
long id = 1;
Query query = session.createQuery("from user where id =" + id);
User emp6 = (User) session.load(User.class, new Long(1));
User user = (User) query.uniqueResult();
List<WashingOrder> washingOrder = user.getOrderList();
washingOrder.add(order);
user.setOrderList(washingOrder);
session.save(user);
Long orderID = (long) 1;
return orderID;
Here if you check I am getting the order list first (user.getOrderList()) and then I am adding the new list and saving the user.
But I want to save the new order list of the user without retrieve the previous order list.
There is any possibility for the adding new order data without retrieve the previous order list of the particular user.
You need to change a mapping
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<WashingOrder> orderList;
}
public class WashingOrder {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, 1L);
WashingOrder order = new WashingOrder();
order.setUser(user);
session.save(order);
You can try to use a fake User instead of loading
WashingOrder order = new WashingOrder();
order.setUser(new User(1L));
session.save(order);

EJB remove entity not working

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();
}

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

I got the above error though i have set the ID manually, Im not using auto generated key here.
when i set the key and pass the object to
entityManager.persist(obj);
it gives the above error.
any help... plz
thanks
This is the InstallationInfo class, and I got the above error when persisting the installationInfo object. The complete error is
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): se.cambio.cimonitor.jpa.table.ModuleInfo
so I have attached the ModuleInfo class as well
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "InstallationInfo", catalog="CI_Monitor", schema="dbo")
public class InstallationInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String installationId;
private String timestamp;
private Module moduleByParentId;
private Environment environmentByEnvironmentClientId;
private Environment environmentByEnvironmentServerId;
private Module moduleByBaseLineId;
private String machineName;
private String status;
private String teamName;
private Set<ModuleInfo> moduleInfos = new HashSet<ModuleInfo>(0);
public InstallationInfo() {
}
public InstallationInfo(String installationId) {
this.installationId = installationId;
}
public InstallationInfo(String installationId,
Module moduleByParentId,
Environment environmentByEnvironmentClientId,
Environment environmentByEnvironmentServerId,
Module moduleByBaseLineId, String machineName,
String status, String teamName,
Set<ModuleInfo> moduleInfos) {
this.installationId = installationId;
this.moduleByParentId = moduleByParentId;
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.machineName = machineName;
this.status = status;
this.teamName = teamName;
this.moduleInfos = moduleInfos;
}
/*#TableGenerator(name="InstlIds", table="InstlPkTb", pkColumnName="InstlId", pkColumnValue="InstlIdVal", allocationSize=1, catalog="CI_Monitor", schema="dbo")
#GeneratedValue(strategy=GenerationType.TABLE, generator="InstlIds")*/
#Id
#Column(name = "InstallationId", unique = true, nullable = false, insertable = true, updatable = true)
public String getInstallationId() {
return this.installationId;
}
public void setInstallationId(String installationId) {
this.installationId = installationId;
}
//#Version This is a bug
#Column(name = "Timestamp")
public String getTimestamp() {
return this.timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentClientId")
public Environment getEnvironmentByEnvironmentClientId() {
return this.environmentByEnvironmentClientId;
}
public void setEnvironmentByEnvironmentClientId(
Environment environmentByEnvironmentClientId) {
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentServerId")
public Environment getEnvironmentByEnvironmentServerId() {
return this.environmentByEnvironmentServerId;
}
public void setEnvironmentByEnvironmentServerId(
Environment environmentByEnvironmentServerId) {
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "MachineName")
public String getMachineName() {
return this.machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
#Column(name = "Status")
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name = "TeamName")
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo", targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}
public void setModuleInfos(Set<ModuleInfo> moduleInfos) {
this.moduleInfos = moduleInfos;
}
}
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "ModuleInfo", catalog="CI_Monitor", schema="dbo")
public class ModuleInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private ModuleInfoId id;
private InstallationInfo installationInfo;
private Module moduleByModuleId;
private Module moduleByParentId;
private Module moduleByBaseLineId;
private String buildNo;
private String svnRevision;
public ModuleInfo() {
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId, Module moduleByParentId,
Module moduleByBaseLineId, String buildNo,
String svnRevision) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
this.moduleByParentId = moduleByParentId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.buildNo = buildNo;
this.svnRevision = svnRevision;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "moduleId", column = #Column(name = "ModuleId", nullable = false)),
#AttributeOverride(name = "installationId", column = #Column(name = "InstallationId", nullable = false)) })
public ModuleInfoId getId() {
return this.id;
}
public void setId(ModuleInfoId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "InstallationId", nullable = false, insertable = false, updatable = false, unique = true)
public InstallationInfo getInstallationInfo() {
return this.installationInfo;
}
public void setInstallationInfo(InstallationInfo installationInfo) {
this.installationInfo = installationInfo;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ModuleId", nullable = false, insertable = false, updatable = false)
public Module getModuleByModuleId() {
return this.moduleByModuleId;
}
public void setModuleByModuleId(Module moduleByModuleId) {
this.moduleByModuleId = moduleByModuleId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "BuildNo")
public String getBuildNo() {
return this.buildNo;
}
public void setBuildNo(String buildNo) {
this.buildNo = buildNo;
}
#Column(name = "SvnRevision")
public String getSvnRevision() {
return this.svnRevision;
}
public void setSvnRevision(String svnRevision) {
this.svnRevision = svnRevision;
}
}
You have a cascade all on ModuleInfos collection, so when you save InstallationInfo it will try to save all the associated ModuleInfos. You need to make sure that the ids of the ModuleInfos are set before saving the InstallationInfo object.
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo",
targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}

Categories