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
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);
}
I would like to use create-or-extend-tables but eclipselink gives below error after tables were created. I am using Eclipselink 2.5.2 and db is MS Sql 2014
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: com.microsoft.sqlserver.jdbc.SQLServerException:
'announcementCOMPANY_ID' object already exists. Error Code: 2714 Call:
ALTER TABLE announcement ADD CONSTRAINT announcementCOMPANY_ID FOREIGN
KEY (COMPANY_ID) REFERENCES company (ID) Query:
DataModifyQuery(sql="ALTER TABLE announcement ADD CONSTRAINT
announcementCOMPANY_ID FOREIGN KEY (COMPANY_ID) REFERENCES company
(ID)")
Persistance.java
persistenceMap.put("javax.persistence.jdbc.driver", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_DRIVER));
persistenceMap.put("javax.persistence.jdbc.user", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_USER));
persistenceMap.put("javax.persistence.jdbc.password", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_PASSWORD));
persistenceMap.put("javax.persistence.jdbc.url", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_URL));
persistenceMap.put("eclipselink.logging.logger",
Log4jSessionLog.class.getName());
// persistenceMap.put("eclipselink.logging.file",
// Log4jSessionLog.class.getName());
persistenceMap
.put("eclipselink.ddl-generation.output-mode", "database");
persistenceMap.put("eclipselink.weaving.internal", "false");
persistenceMap.put("eclipselink.logging.level", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_LOGGING_LEVEL));
persistenceMap.put("eclipselink.ddl-generation",
"create-or-extend-tables");
Announcement.java
#Entity
#Table(name="announcement")
public class Announcement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "annId")
private int id;
#Column(nullable =false, length = 250, name="annName")
private String name;
#Column(length = 250)
private String mainTitle;
#Column(nullable=false, length = 250)
private String subTitle;
#Lob
private String content;
#Column(nullable = false)
private Date startDate;
#Transient
private java.util.Date startDateUtil;
#Column(nullable = false)
private Date endDate;
#Transient
private java.util.Date endDateUtil;
#Lob
private String imgUrl;
#Column(nullable = false)
private boolean isActive;
#Column(nullable = false)
private boolean isDeleted;
#Transient
private BtcResponse status;
private Type type;
#ManyToMany
#JoinTable(name="announcementLogs")
private List<Log> logAList = new ArrayList<Log>();
private Company company;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public java.util.Date getStartDateUtil() {
return startDateUtil;
}
public void setStartDateUtil(java.util.Date startDateUtil) {
this.startDateUtil = startDateUtil;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public java.util.Date getEndDateUtil() {
return endDateUtil;
}
public void setEndDateUtil(java.util.Date endDateUtil) {
this.endDateUtil = endDateUtil;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public List<Log> getLogAList() {
return logAList;
}
public void setLogAList(List<Log> logAList) {
this.logAList = logAList;
}
#ManyToOne
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Announcement() {
super();
}
public Announcement(BtcResponse status) {
super();
this.status = status;
}
public Announcement(java.util.Date startDateUtil,
java.util.Date endDateUtil, String imgUrl, boolean isActive) {
super();
this.startDateUtil = startDateUtil;
this.endDateUtil = endDateUtil;
this.imgUrl = imgUrl;
this.isActive = isActive;
}
#ManyToOne
#JoinColumn(name = "id")
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Company.java
#Entity
#Table(name="company")
public class Company {
#Id
#Column(nullable = false)
private int id;
#Column(length = 100, nullable = false, name="companyName")
private String name;
private List<Banner> bannerList = new ArrayList<Banner>();
private List<Announcement> announcementList = new ArrayList<Announcement>();
private List<PriceList> priceList = new ArrayList<PriceList>();
#OneToMany(mappedBy="company")
public List<Announcement> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(List<Announcement> announcementList) {
this.announcementList = announcementList;
}
#Transient
private BtcResponse status;
public int getId() {
return id;
}
public Company(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy="company")
public List<Banner> getBannerList() {
return bannerList;
}
public void setBannerList(List<Banner> bannerList) {
this.bannerList = bannerList;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public Company() {
super();
}
public Company(BtcResponse status) {
super();
this.status = status;
}
#OneToMany(mappedBy="company")
public List<PriceList> getPriceList() {
return priceList;
}
public void setPriceList(List<PriceList> priceList) {
this.priceList = priceList;
}
}
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();
}
}`
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.