my code is :
List<Session> futureSessions = this.getFutureSession(group.getSessions());
for (Session session: futureSessions) {
Boolean exists = false;
for (SessionDTO sessionDTO: groupDTO.getSessions()) {
if (session.getId() == sessionDTO.getId()) {
exists = true;
}
}
if(false == exists) {
// sessionService.delete(session);
group.getSessions().remove(session);
} else {
exists = false;
}
} Group groupUpdated = groupService.save(group);
This part of code is for remove object (session) into my group object. I use java spring for dilog between angular and java.
I have a relationship between this 2 objects and before save my group object i look for if my session groupServive.save(group) my sessions are not removed from database.
Any help will be very appreciate !
Here is my group model :
`#Entity
#Table(name = "t_group")
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Boolean actif;
private Boolean deleted;
private Enterprise enterprise;
private String avatar;
private Date date_creation;
private Date date_update;
private Integer version;
private Set<User> users;
private List<Rule> rules;
private List<Session> sessions;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(nullable = false, unique = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(nullable = false)
public Boolean getActif() {
return actif;
}
public void setActif(Boolean actif) {
this.actif = actif;
}
#Column(nullable = false)
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#ManyToOne
#JoinColumn(name = "t_enterprise", nullable = true)
public Enterprise getEnterprise() {
return enterprise;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
#Lob
#Column(columnDefinition = "LONGTEXT")
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_update() {
return date_update;
}
public void setDate_update(Date date_update) {
this.date_update = date_update;
}
#ManyToMany
#JoinTable(name = "t_user_group", joinColumns = {
#JoinColumn(name = "t_group", nullable = false) },
inverseJoinColumns = { #JoinColumn(name = "t_user") })
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Session> getSessions() {
return sessions;
}
public void setSessions(List<Session> sessions) {
this.sessions = sessions;
}
#Version
#Column(nullable = false)
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#PreUpdate
private void setLastUpdate() {
this.setDate_update(new Date());
}
#PrePersist
private void setFirstCreationDate() {
this.setLastUpdate();
if(null == this.getDate_creation()){
this.setDate_creation(new Date());
}
}
`
ok, the solution was only to add a method in my sessionDAO
`
#Override
public void delete(Session session) {
// repository.delete(session);
if (session.getId() > 0) {
query = em.createNativeQuery("DELETE FROM `t_session` WHERE `id` = :t_session", Session.class);
query.setParameter("t_session", session.getId());
query.executeUpdate();
}
}`
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 got this error in Spring: enter image description here When I try to join two table entities.
And the foreign key is always Null in DB, Why?
My Entity Classes - Task, ListeExecJob.
Please, help me
Task :
#SuppressWarnings("serial")
#Entity
#Table(name ="task")
public class Task implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;
#Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;
#Column(name = "description", length = 100, nullable = false)
private String description;
#Column(name = "script", length = 100, nullable = false)
private String script;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "date_execution")
private Date date_execution;
#Column(name = "active")
private boolean active;
#ManyToOne
#JoinColumn(name="id_liste")
private ListeExecJob liste;
public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom_job() {
return nom_job;
}
public void setNom_job(String nom_job) {
this.nom_job = nom_job;
}
public String getType_commande() {
return type_commande;
}
public void setType_commande(String type_commande) {
this.type_commande = type_commande;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public boolean getActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Task() {
}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
Date date_execution, boolean active) {
super();
this.id=id;
this.nom_job = nom_job;
this.type_commande = type_commande;
this.description = description;
this.script = script;
this.date_execution = date_execution;
this.active=active ;
}
}
ListeExecJob.java
____________________________________________________
#SuppressWarnings("serial")
#Entity
#Table(name ="liste")
#JsonIgnoreProperties(
value = {"dateCreation"},
allowGetters = true
)
public class ListeExecJob implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idListe")
private int idListe;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "date_creation")
#CreatedDate
private Date date_creation;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#JoinColumn(name = "date_execution")
private Date date_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "fin_execution")
private Date fin_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "next_execution")
private Date next_execution;
#OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JsonIgnore
private List<Task> task;
public int getIdListe() {
return idListe;
}
public void setIdListe(int idListe) {
this.idListe = idListe;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getFin_execution() {
return fin_execution;
}
public void setFin_execution(Date fin_execution) {
this.fin_execution = fin_execution;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonIgnore
public List<Task> getTask() {
if (task == null) {
task = new ArrayList<>();
}
return this.task;
}
public void addTask(Task task) {
getTask().add((Task) task);
((Task) task).setListe(this);
}
public void removeTask(Task task) {
getTask().remove(task);
task.setListe(null);
}
#JsonSetter
public void setTask(List<Task> task) {
this.task = task;
}
public ListeExecJob() {
}
public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b
fin_execution,
Date next_execution) {
super();
this.idListe = idListe;
this.status = status;
this.date_creation = date_creation;
this.date_execution = date_execution;
this.fin_execution = fin_execution;
this.next_execution = next_execution;
}
}
Task service
#Service
#Transactional(propagation= Propagation.SUPPORTS)
#Primary
public class TaskService {
#Autowired
private TaskRepository repository;
#Autowired
private ListeExecJobService service;
#Autowired
public TaskService(TaskRepository repository) {
super();
this.repository = repository;
}
public List<Task> listAllTask(){
return repository.findAll();
}
public Task addTask(Task task){
ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());
ab.addTask(task);
return repository.save(task);
/* task.setListe(ab);
System.out.println(task.getListe().getIdListe());
ab.addTask(task);*/
}
public Task updateTask(Integer id , Task task){
Task job1 = new Task();
job1 = task;
job1.setId(id);
return addTask(job1);
}
public void deleteTask(Integer id){
repository.deleteById(id);
}
public Task getByreferenece(Integer id){
return repository.findById(id).isPresent()? repository.findById(id).get():null;
}
}
ListeExecJobService
#Service
#Transactional
#Primary
public class ListeExecJobService {
#Autowired
private ListeExecJobRepository SJIRepos;
#Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
super();
this.SJIRepos = SJIRepos;
}
public List<ListeExecJob> listAllListeExecJob(){
return SJIRepos.findAll();
}
public ListeExecJob addListeExecJob(ListeExecJob SJI){
return SJIRepos.save(SJI);
}
public ListeExecJob getByreferenece(Integer idListe){
return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;
}
public void deleteListeExecJob(Integer idListe){
SJIRepos.deleteById(idListe);
}
public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
ListeExecJob sji01 = new ListeExecJob();
sji01 = sji;
sji01.setIdListe(idListe);
return addListeExecJob(sji01);
}
public void deleteById(Integer idListe) {
SJIRepos.deleteById(idListe);
}
}
try #JoinColumn(name="id_liste",referencedColumnName = "idListe") in the task class, you have a problem in the join column
I have recently setup a spring + hibernate project. I am using oracle DB. I have a entity as shown in the code.
#Entity
#Table(name = "P_EMP_STATUS")
public class EmployeeStatus extends AbstractEntity<Integer> implements Serializable{
private static final long serialVersionUID = 5451825528280340412L;
private Integer id;
private Region region;
private Project project;
private TaskType taskName;
private String taskType
private PrinceUser princeUser;
private Integer assignee;
private Date actualStartDate;
private Date actualFinishDate;
private Integer scheduledStartDate;
private Integer scheduledFinishDate;
private Integer effortSpent;
private String empComments;
private String mgrcomments;
private String archive;
#Id
#Column(name = "ID")
#GeneratedValue(generator="P_STATUS_SEQ", strategy=GenerationType.AUTO)
#SequenceGenerator(name="P_STATUS_SEQ", sequenceName="P_STATUS_SEQ", allocationSize=1)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "REGION_ID")
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "PROJECT_ID")
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "TASK_ID")
public TaskType getTaskName() {
return taskName;
}
public void setTaskName(TaskType taskName) {
this.taskName = taskName;
}
#Column(name = "TASK_TYPE")
public String getTaskType() {
return taskType;
}
public void setTaskType(String taskType) {
this.taskType = taskType;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "ASSIGNEE")
public PrinceUser getPrinceUser() {
return princeUser;
}
public void setPrinceUser(PrinceUser princeUser) {
this.princeUser = princeUser;
}
#Column(name = "ACT_START")
public Date getActualStartDate() {
return actualStartDate;
}
public void setActualStartDate(Date actualStartDate) {
this.actualStartDate = actualStartDate;
}
#Column(name = "ACT_FINISH")
public Date getActualFinishDate() {
return actualFinishDate;
}
public void setActualFinishDate(Date actualFinishDate) {
this.actualFinishDate = actualFinishDate;
}
#Column(name = "SCH_START")
public Integer getScheduledStartDate() {
return scheduledStartDate;
}
public void setScheduledStartDate(Integer scheduledStartDate) {
this.scheduledStartDate = scheduledStartDate;
}
#Column(name = "SCH_FINISH")
public Integer getScheduledFinishDate() {
return scheduledFinishDate;
}
public void setScheduledFinishDate(Integer scheduledFinishDate) {
this.scheduledFinishDate = scheduledFinishDate;
}
#Column(name = "EFFORT_SPENT")
public Integer getEffortSpent() {
return effortSpent;
}
public void setEffortSpent(Integer effortSpent) {
this.effortSpent = effortSpent;
}
#Column(name = "EMP_COMMENTS")
public String getEmpComments() {
return empComments;
}
public void setEmpComments(String empComments) {
this.empComments = empComments;
}
#Column(name = "MGR_COMMENTS")
public String getMgrcomments() {
return mgrcomments;
}
public void setMgrcomments(String mgrcomments) {
this.mgrcomments = mgrcomments;
}
#Column(name = "ARCHIVE")
public String getArchive() {
return archive;
}
public void setArchive(String archive) {
this.archive = archive;
}
When i try to get data from DB using
Query query = em.createQuery("FROM EmployeeStatus");
return query.getResultList();
I get the following error.
java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CDateAccessor
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
oracle.jdbc.driver.Accessor.unimpl(Accessor.java:358)
I have checked the mappings, everything seems alright. Can someone please help me?
You declared two dates as Integer properties:
private Integer scheduledStartDate;
private Integer scheduledFinishDate;
These fields are probably stored in a column of type Date in database, and the database driver doesn't know how to convert a date to an integer.