public class AfpProcessSummaryDetail implements Serializable {
private String srNo;
private String fileName;
private String status;
private String location;
private String comments;
private Character convertStatus;
private AfpProcessDetail afpProcessDetail;
public AfpProcessSummaryDetail() {
}
public AfpProcessSummaryDetail(String srNo, String fileName, String status, String location, String comments,
AfpProcessDetail afpProcessDetail) {
this.srNo = srNo;
this.fileName = fileName;
this.status = status;
this.location = location;
this.comments = comments;
this.afpProcessDetail = afpProcessDetail;
}
#ManyToOne
#JoinColumn(name = "PROCESSDETAIL")
public AfpProcessDetail getAfpProcessDetail() {
return afpProcessDetail;
}
AfpProcessDetail
public class AfpProcessDetail implements Serializable {
private String processID;
private String processDate;
private Integer fileCount;
private Integer successCount;
private Integer failureCount;
private Character active;
private Set<AfpProcessSummaryDetail> processSummaryDetails = new HashSet<AfpProcessSummaryDetail>(0);
public AfpProcessDetail() {
}
public AfpProcessDetail(String processID, String processDate, Integer fileCount, Integer successCount,
Integer failureCount) {
this.processID = processID;
this.processDate = processDate;
this.fileCount = fileCount;
this.successCount = successCount;
this.failureCount = failureCount;
}
public AfpProcessDetail(String processID, String processDate, Integer fileCount, Integer successCount,
Integer failureCount, Set<AfpProcessSummaryDetail> processSummaryDetails) {
this.processID = processID;
this.processDate = processDate;
this.fileCount = fileCount;
this.successCount = successCount;
this.failureCount = failureCount;
this.processSummaryDetails = processSummaryDetails;
}
#Column(name = "FAILURECOUNT")
public Integer getFailureCount() {
return failureCount;
}
public void setFailureCount(Integer failureCount) {
this.failureCount = failureCount;
}
#Column(name = "FILECOUNT")
public Integer getFileCount() {
return fileCount;
}
public void setFileCount(Integer fileCount) {
this.fileCount = fileCount;
}
#Column(name = "PROCESSDATE")
public String getProcessDate() {
return processDate;
}
public void setProcessDate(String processDate) {
this.processDate = processDate;
}
#Id
#Column(name = "PROCESSID", unique = true, nullable = false)
public String getProcessID() {
return processID;
}
public void setProcessID(String processID) {
this.processID = processID;
}
#Column(name = "SUCESSCOUNT")
public Integer getSuccessCount() {
return successCount;
}
public void setSuccessCount(Integer successCount) {
this.successCount = successCount;
}
#JoinColumn(name="PROCESSDETAIL")
#OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
public Set<AfpProcessSummaryDetail> getProcessSummaryDetails() {
return processSummaryDetails;
}
public void setProcessSummaryDetails(Set<AfpProcessSummaryDetail> processSummaryDetails) {
this.processSummaryDetails = processSummaryDetails;
}
Code for updating
public String updateSummaryDetails(ViewFile viewFile, String codeID) {
if (viewFile != null && codeID != null) {
HibernateTemplate transactionTemplate = new HibernateTemplate(sessionFactory, true);
Object result = transactionTemplate.execute(new HibernateCallback<Object>() {
#Override
public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
AfpProcessSummaryDetail processSummary =null,newProcessSummary =null;
AfpProcessDetail processDetail = (AfpProcessDetail)session.get(AfpProcessDetail.class,codeID);
List<FileProperty> fileList = viewFile.getFileList();
Set<AfpProcessSummaryDetail> setProcessSummary=new HashSet<AfpProcessSummaryDetail>();
Set<AfpProcessSummaryDetail> modSetProcessSummary=new HashSet<AfpProcessSummaryDetail>();
setProcessSummary =processDetail.getProcessSummaryDetails();
Iterator<AfpProcessSummaryDetail> itrProcessSumm=setProcessSummary.iterator();
int srNo = 0;
while (itrProcessSumm.hasNext()){
processSummary =(AfpProcessSummaryDetail)itrProcessSumm.next();
for (FileProperty fileProperty : fileList) {
newProcessSummary =new AfpProcessSummaryDetail();
newProcessSummary.setSrNo(codeID + "" + srNo);
newProcessSummary.setFileName(fileProperty.getName());
newProcessSummary.setLocation(fileProperty.getPath());
newProcessSummary.setComments(fileProperty.getComment());
newProcessSummary.setStatus(fileProperty.getStatus());
newProcessSummary.setConvertStatus(fileProperty.getConvertStatus());
newProcessSummary.setAfpProcessDetail(processDetail);
modSetProcessSummary.add(newProcessSummary);
/*if (processSummary.getFileName().trim().equals(fileProperty.getName().trim())){
System.out.println("Element removed");
itrProcessSumm.remove();
modSetProcessSummary.add(newProcessSummary);
break;
}*/
srNo++;
}
}
// setProcessSummary.addAll(modSetProcessSummary);
processDetail.setProcessSummaryDetails(modSetProcessSummary);
processDetail.setFailureCount(viewFile.getExceptionNo());
processDetail.setSuccessCount(viewFile.getSuccessNo());
processDetail.setActive(viewFile.getActive());
transactionTemplate.flush();
session.merge(processDetail);
System.out.println("updated successfully");
return codeID;
}
});
Desired result
I want to perform a one to many update -AfpProcessSummaryDetail which is related to AfpProcessDetail via Set. When I try to replace the set values for update it tries to update the primary key to null. If I don't replace the updates don't take place. If I set cascade it gives error -a different object with the same identifier value was already associated with the session:
[com.aurionpro.convertor.dto.AfpProcessSummaryDetail#15a236ffc961];
nested exception is org.hibernate.NonUniqueObjectException: a
different object with the same identifier value was already associated
with the session.
Please suggest
Related
So I'm making an API using Java Spring-boot and JBDC with PostgreSQL as the database and Postman for testing. All the basic CRUD function is already implemented, but I'm trying to validates if a value in the POST request is already in the database or not so there are no duplicate data.
Here's the model:
package com.akuntansi.akuntansi.model;
import java.sql.Timestamp;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
public class mAkuntansi {
private Integer id_md_jurnal_Integer;
private Integer id_dd_wilayah_kerja;
private String kode_file;
private String file_id;
private String tanggal;
private String debet_kredit;
private String kode_coa;
private long nominal;
private Integer flag;
private Integer id_akmt_subledger;
private Integer id_referensi;
private String no_bukti;
private Timestamp created_date;
public mAkuntansi(){}
public mAkuntansi(Integer id_md_jurnal_Integer, Integer id_dd_wilayah_kerja, String kode_file, String file_id, String tanggal, String debet_kredit, String kode_coa,
long nominal, Integer flag, Integer id_akmt_subledger, Integer id_referensi, String no_bukti, Timestamp created_date){
this.id_md_jurnal_Integer = id_md_jurnal_Integer;
this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
this.kode_file = kode_file;
this.file_id = file_id;
this.tanggal = tanggal;
this.debet_kredit = debet_kredit;
this.kode_coa = kode_coa;
this.nominal = nominal;
this.flag = flag;
this.id_akmt_subledger = id_akmt_subledger;
this.id_referensi = id_referensi;
this.no_bukti = no_bukti;
this.created_date = created_date;
}
public mAkuntansi(Integer id_dd_wilayah_kerja, String kode_file, String file_id, String tanggal, String debet_kredit, String kode_coa,
long nominal, Integer flag, Integer id_akmt_subledger, Integer id_referensi, String no_bukti, Timestamp created_date){
this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
this.kode_file = kode_file;
this.file_id = file_id;
this.tanggal = tanggal;
this.debet_kredit = debet_kredit;
this.kode_coa = kode_coa;
this.nominal = nominal;
this.flag = flag;
this.id_akmt_subledger = id_akmt_subledger;
this.id_referensi = id_referensi;
this.no_bukti = no_bukti;
this.created_date = created_date;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getid_md_jurnal_int(){
return id_md_jurnal_Integer;
}
public void setid_md_jurnal_int(Integer id_md_jurnal_Integer){
this.id_md_jurnal_Integer = id_md_jurnal_Integer;
}
public Integer getid_dd_wilayah_kerja(){
return id_dd_wilayah_kerja;
}
public void setid_dd_wilayah_kerja(Integer id_dd_wilayah_kerja){
this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
}
public String getkode_file(){
return kode_file;
}
public void setkode_file(String kode_file){
this.kode_file = kode_file;
}
public String getfile_id(){
return file_id;
}
public void setfile_id(String file_id){
this.file_id = file_id;
}
public String gettanggal(){
return tanggal;
}
public void settanggal(String tanggal){
this.tanggal = tanggal;
}
public String getdebet_kredit(){
return debet_kredit;
}
public void setdebet_kredit(String debet_kredit){
this.debet_kredit = debet_kredit;
}
public String getkode_coa(){
return kode_coa;
}
public void setkode_coa(String kode_coa){
this.kode_coa = kode_coa;
}
public long getnominal(){
return nominal;
}
public void setnominal(long nominal){
this.nominal = nominal;
}
public Integer getflag(){
return flag;
}
public void setflag(Integer flag){
this.flag = flag;
}
public Integer getid_akmt_subledger(){
return id_akmt_subledger;
}
public void setid_akmt_subledger(Integer id_akmt_subledger){
this.id_akmt_subledger = id_akmt_subledger;
}
public Integer getid_referensi(){
return id_referensi;
}
public void setid_referensi(Integer id_refrensi){
this.id_referensi = id_refrensi;
}
public String getno_bukti(){
return no_bukti;
}
public void setno_bukti(String no_bukti){
this.no_bukti = no_bukti;
}
public Timestamp getcreated_date(){
return created_date;
}
public void setcreated_date(Timestamp created_date){
this.created_date = created_date;
}
}
Let say for example I want to validates the kode_coa. There's a POST request with kode_coa of K1 but in the database, a data with value K1 already exist, how do you prevent a duplicate data from getting inserted into the database?
in this case, i want to show Json to an response page in java hibernate, query method from DAO like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("FROM TransactionQR tr, Batch b, Terminal t, User_Smartphone us, Merchant mc WHERE tr.batch = b.id AND b.user_smartphone = us.id AND b.terminal = t.id AND t.merchant = mc.id AND state = '1' ").list();
}
then in servlet class i try to convert the list into json using Json object and json array then write in response like this:
int start = 0;
String jsonResult = null;
JSONObject jo=new JSONObject();
HttpServletRequest request = context.getRequest();
HttpServletResponse response = context.getResponse();
HttpSession session = context.getSession();
DB db = getDB(context);
//JSONObject jo = new JSONObject();
QRTransactionDao QR = new QRTransactionDao(db);
//Gson objGson = new GsonBuilder().setPrettyPrinting().create();
//String json = objGson.toJson(QR.getAllTransaction());
//System.out.println(json);
List<TransactionQR> str = QR.getAllTransaction();
JSONArray array = new JSONArray();
for(TransactionQR tr : str){
JSONObject str3 = new JSONObject();
str3.put("amount", tr.getAmount());
context.put("jsoncontent", jsonResult);
array.add(str3);
}
jo.put("status", "ok");
jo.put("dataqr", array);
jsonResult=jo.toString();
response.setContentType("application/json");
response.getWriter().print(jsonResult);
but i got the error on syntax in this line loop:
for(TransactionQR tr : str){
the error like this:
[Ljava.lang.Object; cannot be cast to Transaction
here the model Transaction:
package id.co.keriss.consolidate.ee;
import java.io.Serializable;
import java.util.Date;
public class TransactionQR implements Serializable{
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
i have try to handle the list with Gson:
Gson objGson = new GsonBuilder().setPrettyPrinting().create();
String json = objGson.toJson(QR.getAllTransaction());
System.out.println(json);
in that way, it's work to show but it's not from POJO right i want work with pojo to parse the data to json ?
why i get the error can't cast to model ? any clue ?
Try adding Select tr to your query in getAllTransaction()
Wich is the relation between QRTransactionDao and TransactionQR ?
I'm new to JavaFX, and I'm sorry if this sound stupid. I'm working on a desktop app to display data from the database. I'm using JPA Hibernate.
This is a database of contractors and contracts, by getting the startdate of contract and contract duration from input, I want to be able to calculate the end date and display it to the table.
I created the method to calculate endDate, by the adding the number of month to the start date, but the problem is how do I display it on the Table.
Look at controller class:
package energiadata.controller;
public class ActiveContractTabController {
private ObservableList<ActiveContractor> dataActive = FXCollections.observableArrayList();
#FXML
private VBox vBox;
#FXML
private TextField tfContractor;
#FXML
private TextField tfNatureOfContract;
#FXML
private TextField tfUser_dept;
#FXML
private TextField tfValue;
#FXML
private TextField tfValueRate;
#FXML
public DatePicker startDatePicker;
#FXML
public TextField tfContractDuration;
#FXML
private TextField tfremarks;
#FXML
private ChoiceBox<String> choiceBox;
#FXML
private Button addContractButton;
#FXML
private TextArea resultAreaActive;
#FXML
private TableView<ActiveContractor> activeContractTable;
#FXML
private TableColumn<ActiveContractor, Integer> idColumn;
#FXML
private TableColumn<ActiveContractor, String> contractorColumn;
#FXML
private TableColumn<ActiveContractor, String> natureOfContractColumn;
#FXML
private TableColumn<ActiveContractor, String> user_deptColumn;
#FXML
private TableColumn<ActiveContractor, Integer> valueNairaColumn;
#FXML
private TableColumn<ActiveContractor, Integer> valueDollarColumn;
#FXML
private TableColumn<ActiveContractor, LocalDate> start_dateColumn;
#FXML
private TableColumn<ActiveContractor, LocalDate> end_dateColumn;
#FXML
private TableColumn<ActiveContractor, String> contractTypeColumn;
#FXML
private TableColumn<ActiveContractor, String> remarksColumn;
#FXML
private Button allContractsButton;
#FXML
private Button updateButton;
#FXML
private Button deleteButton;
public void setupTableActive() {
idColumn.setCellValueFactory(cellData -> cellData.getValue().idAProperty().asObject());
contractorColumn.setCellValueFactory(cellData -> cellData.getValue().contractor());
natureOfContractColumn.setCellValueFactory(cellData -> cellData.getValue().natureOfContract());
user_deptColumn.setCellValueFactory(cellData -> cellData.getValue().user_dept());
valueNairaColumn.setCellValueFactory(cellData -> cellData.getValue().value().asObject());
valueDollarColumn.setCellValueFactory(cellData -> cellData.getValue().valueMain().asObject());
start_dateColumn.setCellValueFactory(cellData -> cellData.getValue().start_date());
end_dateColumn.setCellValueFactory(cellData -> cellData.getValue().end_date());
contractTypeColumn.setCellValueFactory(cellData -> cellData.getValue().contractType());
remarksColumn.setCellValueFactory(cellData -> cellData.getValue().remarks());
}
#FXML
void addButton(ActionEvent actionEvent) {
String contractor = tfContractor.getText();
String natureOfContract = tfNatureOfContract.getText();
String user_dept = tfUser_dept.getText();
Integer value = Integer.parseInt(tfValue.getText());
Integer valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate start_date = startDatePicker.getValue();
Integer contractDuration = Integer.parseInt(tfContractDuration.getText());
String contractType = choiceBox.getValue();
String remarks = tfremarks.getText();
ActiveContractor activeContractor = new ActiveContractor(contractor, natureOfContract, user_dept, value, valueRate, start_date, contractDuration, remarks, contractType);
try {
activeContractTable.getItems().add(activeContractor);
DBUtil.saveActiveContractor(activeContractor);
resultAreaActive.setText("Active Contract Added");
} catch (Exception e) {
resultAreaActive.setText("Error adding active contract" + e);
}
}
#FXML
void deleteActiveContractor(ActionEvent actionEvent) {
activeContractTable.getItems().remove(activeContractTable.getSelectionModel().getSelectedItem());
DBUtil.removeActiveContractor(activeContractTable.getSelectionModel().getSelectedItem());
resultAreaActive.setText(" Contractor Deleted! ");
}
#FXML
void updateActiveContractorDetails(ActionEvent actionEvent) {
ActiveContractor activeContractor = activeContractTable.getSelectionModel().getSelectedItem();
String _contractor = tfContractor.getText();
String _natureOfContract = tfNatureOfContract.getText();
String _user_dept = tfUser_dept.getText();
Integer _value = Integer.parseInt(tfValue.getText());
Integer _valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate _start_date = startDatePicker.getValue();
Integer _contractDuration = Integer.parseInt(tfContractDuration.getText());
String _remarks = tfremarks.getText();
try {
DBUtil.updateActiveContractor(activeContractor);
activeContractTable.getItems().add(activeContractor);
activeContractTable.toFront();
resultAreaActive.setText(_contractor + "updated Successfully!");
} catch (Exception e) {
resultAreaActive.setText("Could not update the Database" + e);
}
}
#FXML
void getActiveContractorList(ActionEvent actionEvent) {
EntityManager em = DBUtil.getEntityManager();
List<ActiveContractor> list = em.createQuery("SELECT a FROM ActiveContractor a", ActiveContractor.class).getResultList();
if (dataActive == null) {
dataActive = FXCollections.observableArrayList(list);
} else {
dataActive.clear();
dataActive.addAll(list);
}
activeContractTable.setItems(dataActive);
// contractorTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
setupTableActive();
resultAreaActive.setText(" List Display! ");
}
ActiveContractor activeContract;
public LocalDate changeEndDateProperty() {
LocalDate localdate = startDatePicker.getValue();
LocalDate end_localDate = localdate.plusMonths(Long.valueOf(tfContractDuration.getText()));
return end_localDate;
}
public Integer valueRateCal() {
Integer valueMainDollar = Integer.parseInt(tfValue.getText())
* Integer.parseInt(tfValueRate.getText());
return valueMainDollar;
}
#FXML
public void initialize() {
setupTableActive();
choiceBox.setItems(FXCollections.observableArrayList("One-Off", "Running"));
}
}
And Entity Class:
package energiadata.model;
public class ActiveContractor implements Externalizable {
private static final long serialVersionUID = 1L;
private IntegerProperty idA;
private int _idA;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "id")
public final int getId() {
if (idA == null) {
return _idA;
} else {
return idA.get();
}
}
public final void setId(int id) {
if (this.idA == null) {
_idA = id;
} else {
this.idA.set(id);
}
}
public IntegerProperty idAProperty() {
if (idA == null) {
idA = new SimpleIntegerProperty(this, "id", _idA);
}
return idA;
}
private StringProperty contractor;
private String _contractor;
#Basic(optional = false)
#Column(name = "contractor")
public final String getContractor() {
if (this.contractor == null) {
return _contractor;
} else {
return contractor.get();
}
}
public final void setContractor(String contractor) {
if (this.contractor == null) {
_contractor = contractor;
} else {
this.contractor.set(contractor);
}
}
public StringProperty contractor() {
if (contractor == null) {
contractor = new SimpleStringProperty(this, "contractor", _contractor);
}
return contractor;
}
private StringProperty natureOfContract;
private String _natureOfContract;
#Basic(optional = false)
#Column(name = "natureOfContract")
public final String getNatureOfContract() {
if (this.natureOfContract == null) {
return _natureOfContract;
} else {
return natureOfContract.get();
}
}
public final void setNatureOfContract(String natureOfContract) {
if (this.natureOfContract == null) {
_natureOfContract = natureOfContract;
} else {
this.natureOfContract.set(natureOfContract);
}
}
public StringProperty natureOfContract() {
if (natureOfContract == null) {
natureOfContract = new SimpleStringProperty(this, "natureOfContract", _natureOfContract);
}
return natureOfContract;
}
private StringProperty user_dept;
private String _user_dept;
#Basic(optional = false)
#Column(name = "user_dept")
public final String getUser_dept() {
if (this.user_dept == null) {
return _user_dept;
} else {
return user_dept.get();
}
}
public final void setUser_dept(String user_dept) {
if (this.user_dept == null) {
_user_dept = user_dept;
} else {
this.user_dept.set(user_dept);
}
}
public StringProperty user_dept() {
if (user_dept == null) {
user_dept = new SimpleStringProperty(this, "user_dept", _user_dept);
}
return user_dept;
}
private IntegerProperty value;
private int _value;
#Basic(optional = false)
#Column(name = "value")
public final Integer getValue() {
if (this.value == null) {
return _value;
} else {
return value.get();
}
}
public final void setValue(Integer value) {
if (this.value == null) {
_value = value;
} else {
this.value.set(value);
}
}
public IntegerProperty value() {
if (value == null) {
value = new SimpleIntegerProperty(this, "value", _value);
}
return value;
}
private IntegerProperty valueMain;
private Integer _valueMain;
#Basic(optional = false)
#Column(name = "valueMain")
public final Integer getValueMain() {
if (this.valueMain == null) {
return _valueMain;
} else {
return valueMain.get();
}
}
public final void setValueMain(Integer valueMain) {
if (this.valueMain == null) {
_valueMain = valueMain;
} else {
this.value.set(valueMain);
}
}
public IntegerProperty valueMain() {
if (valueMain == null) {
valueMain = new SimpleIntegerProperty(this, "valueMain", _valueMain);
}
return valueMain;
}
private IntegerProperty valueRate;
private int _valueRate;
#Basic(optional = false)
#Column(name = "valueRate")
public final Integer getValueRate() {
if (this.valueRate == null) {
return _valueRate;
} else {
return valueRate.get();
}
}
public final void setValueRate(Integer valueRate) {
if (this.valueRate == null) {
_valueMain = valueRate;
} else {
this.value.set(valueRate);
}
}
public IntegerProperty valueRate() {
if (valueMain == null) {
valueMain = new SimpleIntegerProperty(this, "valueMain", _valueRate);
}
return valueRate;
}
private SimpleObjectProperty<LocalDate> start_date;
private LocalDate _start_date;
#Basic(optional = false)
#Column(name = "start_date")
public final LocalDate getStart_date() {
if (this.start_date == null) {
return _start_date;
} else {
return start_date.get();
}
}
public final void setStart_date(LocalDate start_date) {
if (this.start_date == null) {
_start_date = start_date;
} else {
this.start_date.set(start_date);
}
}
public SimpleObjectProperty start_date() {
if (start_date == null) {
start_date = new SimpleObjectProperty<>(this, "start_date", _start_date);
}
return start_date;
}
private ObjectProperty<LocalDate> end_date;
private LocalDate _end_date;
#Basic(optional = false)
#Column(name = "end_date")
public final LocalDate getEnd_date() {
if (this.end_date == null) {
return _end_date;
} else {
return end_date.get();
}
}
public final void setEnd_date(LocalDate end_date) {
if (this.end_date == null) {
_end_date = end_date;
} else {
this.end_date.set(end_date);
}
}
public ObjectProperty end_date() {
if (end_date == null) {
end_date = new SimpleObjectProperty<>(this, "end_date", _end_date);
}
return end_date;
}
private IntegerProperty contractDuration;
private Integer _contractDuration;
#Basic(optional = false)
#Column(name = "contractDuration")
public final Integer getContractDuration() {
if (this.contractDuration == null) {
return _contractDuration;
} else {
return contractDuration.get();
}
}
public final void setContractDuration(Integer contractDuration) {
if (this.contractDuration == null) {
_contractDuration = contractDuration;
} else {
this.value.set(contractDuration);
}
}
public IntegerProperty contractDuration() {
if (contractDuration == null) {
contractDuration = new SimpleIntegerProperty(this, "contractDuration", _contractDuration);
}
return contractDuration;
}
private StringProperty remarks;
private String _remarks;
#Basic(optional = false)
#Column(name = "remarks")
public final String getRemarks() {
if (this.remarks == null) {
return _remarks;
} else {
return remarks.get();
}
}
public final void setRemarks(String remarks) {
if (this.remarks == null) {
_remarks = remarks;
} else {
this.remarks.set(remarks);
}
}
public StringProperty remarks() {
if (remarks == null) {
remarks = new SimpleStringProperty(this, "remarks", _remarks);
}
return remarks;
}
private StringProperty contractType;
private String _contractType;
#Basic(optional = false)
#Column(name = "contractType")
public final String getContractType() {
if (this.contractType == null) {
return _contractType;
} else {
return contractType.get();
}
}
public final void setContractType(String contractType) {
if (this.contractType == null) {
_contractType = contractType;
} else {
this.contractType.set(contractType);
}
}
public StringProperty contractType() {
if (contractType == null) {
contractType = new SimpleStringProperty(this, "contractType", _contractType);
}
return contractType;
}
public ActiveContractor() {
}
public ActiveContractor(String _contractor, String _natureOfContract, String _user_dept, int _value, int _valueRate, LocalDate _start_date, Integer _contractDuration, String _remarks, String _contractType) {
this._contractor = _contractor;
this._natureOfContract = _natureOfContract;
this._user_dept = _user_dept;
this._value = _value;
this._valueRate = _valueRate;
this._start_date = _start_date;
this._contractDuration = _contractDuration;
this._remarks = _remarks;
this._contractType = _contractType;
}
public ActiveContractor(StringProperty contractor, StringProperty natureOfContract, StringProperty user_dept, IntegerProperty value, IntegerProperty valueRate, SimpleObjectProperty<LocalDate> start_date, IntegerProperty contractDuration, StringProperty remarks, StringProperty contractType) {
this.contractor = contractor;
this.natureOfContract = natureOfContract;
this.user_dept = user_dept;
this.value = value;
this.valueRate = valueRate;
this.start_date = start_date;
this.contractDuration = contractDuration;
this.remarks = remarks;
this.contractType = contractType;
}
#Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(getId());
out.writeObject(getContractor());
out.writeObject(getNatureOfContract());
out.writeObject(getUser_dept());
out.writeObject(getValue());
out.writeObject(getValueMain());
out.writeObject(getValueRate());
out.writeObject(getStart_date());
out.writeObject(getEnd_date());
out.writeObject(getContractDuration());
out.writeObject(getRemarks());
out.writeObject(contractType());
}
#Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
setId(in.readInt());
setContractor((String) in.readObject());
setNatureOfContract((String) in.readObject());
setUser_dept((String) in.readObject());
setValue((Integer) in.readObject());
setValueMain((Integer) in.readObject());
setValueRate((Integer) in.readObject());
setStart_date((LocalDate) in.readObject());
setEnd_date((LocalDate) in.readObject());
setContractDuration((Integer) in.readObject());
setRemarks((String) in.readObject());
setContractType((String) in.readObject());
}
}
Since the Methods in not the Entity, I couldn't add it to the column... I've been on this for days.
My question is different from How can I add rows and columns to a JavaFX 8 TableView.
I already add columns to my tableview, check my setupTableActive() method above. What I'm trying to do is, for example, the end_dateColumn, I want to be able to get value fron DatePicker and add some months to it, then set it to the end_dateColumn. But by default, it only allows me to put Property method in the entity class there. Hope this is clear enough...
Ok, I see a lot happening here that needs a bit of work, but lets just look at your issue and you can sort the rest out yourself. From what I can tell it looks like you dont ever pass your end_date to the activeContractTable TableView and therefore the end_date will never be added to the Table no matter how hard you try, but you can fix this quite easily by adding and adjusting several lines of code as shown below:
Note my comments starting with //======
In the ActiveContractTabController class addButton method:
#FXML
void addButton(ActionEvent actionEvent) {
String contractor = tfContractor.getText();
String natureOfContract = tfNatureOfContract.getText();
String user_dept = tfUser_dept.getText();
Integer value = Integer.parseInt(tfValue.getText());
Integer valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate start_date = startDatePicker.getValue();
//====== You need to add the end date here =====//
LocalDate end_date = changeEndDateProperty();
Integer contractDuration = Integer.parseInt(tfContractDuration.getText());
String contractType = choiceBox.getValue();
String remarks = tfremarks.getText();
//====== You need to add the end date to the line below, and modify ActiveContractor to receive the extra end_date variable =====//
ActiveContractor activeContractor = new ActiveContractor(contractor, natureOfContract, user_dept, value, valueRate, start_date, end_date, contractDuration, remarks, contractType);
In the ActiveContractor class:
//====== You need to add the end date to the line below as one of this methods inputs so it accepts the call from ActiveContractTabController =====//
public ActiveContractor(String _contractor, String _natureOfContract, String _user_dept, int _value, int _valueRate, LocalDate _start_date, LocalDate _end_date, Integer _contractDuration, String _remarks, String _contractType) {
this._contractor = _contractor;
this._natureOfContract = _natureOfContract;
this._user_dept = _user_dept;
this._value = _value;
this._valueRate = _valueRate;
this._start_date = _start_date;
//====== You need to add the end date here =====//
this._end_date = _end_date;
this._contractDuration = _contractDuration;
this._remarks = _remarks;
this._contractType = _contractType;
}
//====== You need to add the end date to the line below as one of this methods inputs so it accepts the call from ActiveContractTabController =====//
public ActiveContractor(StringProperty contractor, StringProperty natureOfContract, StringProperty user_dept, IntegerProperty value, IntegerProperty valueRate, SimpleObjectProperty<LocalDate> start_date, SimpleObjectProperty<LocalDate> end_date, IntegerProperty contractDuration, StringProperty remarks, StringProperty contractType) {
this.contractor = contractor;
this.natureOfContract = natureOfContract;
this.user_dept = user_dept;
this.value = value;
this.valueRate = valueRate;
this.start_date = start_date;
//====== You need to add the end date here =====//
this.end_date = end_date;
this.contractDuration = contractDuration;
this.remarks = remarks;
this.contractType = contractType;
}
I have not tested or checked this code, so you may need to make other adjustments for it to work as intended, but it should give you an idea.
I have a Client.class which has a OneToMany relation with Posto.class.
#Entity
#Table(name = "client", catalog = "SMARTPARK")
public class Client implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idClient;
private String nomeClient;
private int numPosti;
private int numLuci;
private String currentIp;
private boolean online;
private String prop;
private SortedSet<Posto> posti = new TreeSet<>();
private SortedSet<Luce> luci = new TreeSet<>();
public Client() {
}
public Client(int idClient, String nomeClient, int numPosti, int numLuci,
String currentIp, boolean online, String prop,
SortedSet<Posto> posti, SortedSet<Luce> luci) {
this.idClient = idClient;
this.nomeClient = nomeClient;
this.numPosti = numPosti;
this.numLuci = numLuci;
this.currentIp = currentIp;
this.prop = prop;
this.online = online;
this.posti = posti;
this.luci = luci;
}
#Id
#Column(name = "id_client", unique = true, nullable = false)
public int getIdClient() {
return this.idClient;
}
public void setIdClient(int idClient) {
this.idClient = idClient;
}
#Column(name = "nome_client", nullable = false, length = 65535)
public String getNomeClient() {
return this.nomeClient;
}
public void setNomeClient(String nomeClient) {
this.nomeClient = nomeClient;
}
#Transient
public int getNumPosti() {
return this.numPosti;
}
public void setNumPosti(int numPosti) {
this.numPosti = numPosti;
}
#Transient
public int getNumLuci() {
return this.numLuci;
}
public void setNumLuci(int numLuci) {
this.numLuci = numLuci;
}
#Column(name = "client_ip", nullable=true)
public String getCurrentIp() {
return currentIp;
}
public void setCurrentIp(String currentIp) {
this.currentIp = currentIp;
}
#Column(name="online")
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
#Column(name="prop")
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
#OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client", orphanRemoval=true)
#OrderBy("numeroPosto ASC")
public Set<Posto> getPosti() {
return posti;
}
public void setPosti(SortedSet<Posto> posti) {
this.posti = posti;
}
#OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "client", orphanRemoval=true)
#OrderBy("numeroLuce ASC")
public SortedSet<Luce> getLuci() {
return luci;
}
public void setLuci(SortedSet<Luce> luci) {
this.luci = luci;
}
This was made because a use the Set in a responseEntity Controller and I need to preserve the order of how postiis displayed in the Json output.
So in Posto.class I implemented Comparable interface, overrding the compareTo method
#Override
public int compareTo(Posto o) {
if(this.numeroPosto == o.numeroPosto){
return 0;
} else {
return this.numeroPosto > o.numeroPosto ? 1 : -1;
}
Now, when calling my controller, i got this error from Hibernate:
2016-03-30 16:18:07.486 ERROR [http-nio-8080-exec-6]: HHH000123: IllegalArgumentException in class: it.besmart.models.Client, setter method of property: posti
2016-03-30 16:18:07.486 ERROR [http-nio-8080-exec-6]: HHH000091: Expected type: java.util.SortedSet, actual value: org.hibernate.collection.internal.PersistentSet
How can i solve it? Hibernate changes my SortedSet in a PersistentSet, do I have to use this one to set my posti with the order i want?
The problem is you defined your posti and Luci as concrete SortSet. Hibernate PersistentSet implements generic Set interface. All you need to do is changing SortSet to generic Set and modify getters, setters accordingly.
private Set<Posto> posti;
private Set<Luce> luci;
I have a problem with Hibernate 4.3.0Final that I have been unable to solve. It is puzzling because I am running similar code in several other places which is working fine. The below code is throwing a java.lang.NullPointerException. It is running in a web service in using a NetBeans setup using Glassfish and JavaDB.
The exception is thrown after item.setRoomId(-1);:
characterId, characterFirstName, roomId, k, variables are being passed in from above; I have verified via debugging that they all have values with valid datatypes; also a valid record is in the Items table.
Query itemsQuery = em.createNamedQuery("Items.findByRoomIdByName");
itemsQuery.setParameter("roomId", roomId);
itemsQuery.setParameter("name", itemName);
Items item = null;
if (itemsQuery.getResultList().isEmpty()) {
throw new UnableToIdentifyException("Item does not exist! You cannot get an item that does not exist. Did you already pick it up?");
}
else {
item = (Items) itemsQuery.getSingleResult();
Boolean isStuck = item.getIsUnmovable();
if (isStuck) {
//Item stuck
notifyItemGetViewers(characterId, characterFirstName, roomId, itemName, isStuck);
}
else {
//Pick up item
try {
item.setRoomId(-1);
item.setCharacterId(characterId);
item.setStoreId(-1);
}
catch (Exception e) {
logger.severe("Wrapped Exection Caught: Exception: " + e.toString() + " Error Message: " + e.getMessage());
}
em.persist(item);
em.flush();
notifyItemGetViewers(characterId, characterFirstName, roomId, itemName, isStuck);
}
}
Entity class (Items.java)
package org.tav.mit;
import java.beans.*;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name = "mit_items")
#NamedQueries({
#NamedQuery(name="Items.findByItemId",
query="SELECT i FROM Items i WHERE i.itemId = :itemId"),
#NamedQuery(name="Items.findByRoomIdByName",
query="SELECT i FROM Items i WHERE i.roomId = :roomId AND i.name = :name"),
#NamedQuery(name="Items.findByRoomId",
query="SELECT i FROM Items i WHERE i.roomId = :roomId"),
#NamedQuery(name="Items.findByCharacterId",
query="SELECT i FROM Items i WHERE i.characterId = :characterId"),
#NamedQuery(name="Items.findByStoreId",
query="SELECT i FROM Items i WHERE i.storeId = :storeId"),
#NamedQuery(name="Items.findByName",
query="SELECT i FROM Items i WHERE i.name = :name")
})
public class Items implements Serializable {
public static final String PROP_ITEMID = "itemIdProperty";
public static final String PROP_ROOMID = "roomIdProperty";
public static final String PROP_CHARACTERID = "characterIdProperty";
public static final String PROP_STOREID = "storeIdProperty";
public static final String PROP_NAME = "nameProperty";
public static final String PROP_DESCRIPTION = "descriptionProperty";
public static final String PROP_TYPE = "typeProperty";
public static final String PROP_WORTH = "worthProperty";
public static final String PROP_BODYLOCATION = "bodyLocationProperty";
public static final String PROP_ISUNMOVABLE = "isUnmovableProperty";
public static final String PROP_ACBONUS = "acBonusProperty";
public static final String PROP_USETIMEDELAY = "useTimeDelayProperty";
public static final String PROP_DAMAGEDICE = "damageDiceProperty";
public static final String PROP_DAMAGEDICESIDES = "damageDiceSidesProperty";
public static final String PROP_DAMAGETYPE = "damageTypeProperty";
public static final String PROP_LIGHTPROVIDED = "lightProvidedProperty";
#Id
#GeneratedValue
private Integer itemId;
#Column()
private Integer roomId = -1;
#Column()
private Integer characterId = -1;
#Column()
private Integer storeId = -1;
#Column(length = 128, nullable = false)
private String name;
#Column(length = 2048, nullable = true)
private String description;
#Column()
private Integer type = -1;
#Column()
private Double worth = 0.0;
#Column()
private Integer bodyLocation = -1;
#Column(nullable = false)
private Boolean isUnmovable = false;
#Column()
private Integer acBonus = -1;
#Column()
private Integer useTimeDelay = -1;
#Column()
private Integer damageDice = -1;
#Column()
private Integer damageDiceSides = -1;
#Column()
private Integer damageType = -1;
#Column(nullable = false)
private Boolean lightProvided = false;
#Column(length = 2048)
private PropertyChangeSupport propertySupport;
public Items()
{
propertySupport = new PropertyChangeSupport(this);
}
public int getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
Integer oldValue = this.itemId;
this.itemId = itemId;
propertySupport.firePropertyChange(PROP_ITEMID, oldValue, itemId);
}
public int getRoomId() {
return roomId;
}
public void setRoomId(Integer roomId) {
Integer oldValue = this.roomId;
this.roomId = roomId;
propertySupport.firePropertyChange(PROP_ROOMID, oldValue, roomId);
}
public int getCharacterId() {
return characterId;
}
public void setCharacterId(Integer characterId) {
Integer oldValue = this.characterId;
this.characterId = characterId;
propertySupport.firePropertyChange(PROP_CHARACTERID, oldValue, characterId);
}
public int getStoreId() {
return storeId;
}
public void setStoreId(Integer storeId) {
Integer oldValue = this.storeId;
this.storeId = storeId;
propertySupport.firePropertyChange(PROP_STOREID, oldValue, storeId);
}
public String getName() {
return name;
}
public void setName(String name) {
String oldValue = this.name;
this.name = name;
propertySupport.firePropertyChange(PROP_NAME, oldValue, name);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
String oldValue = this.description;
this.description = description;
propertySupport.firePropertyChange(PROP_DESCRIPTION, oldValue, description);
}
public int getType() {
return type;
}
public void setType(Integer type) {
Integer oldValue = this.type;
this.type = type;
propertySupport.firePropertyChange(PROP_TYPE, oldValue, type);
}
public double getWorth() {
return worth;
}
public void setWorth(double worth) {
double oldValue = this.worth;
this.worth = worth;
propertySupport.firePropertyChange(PROP_WORTH, oldValue, worth);
}
public int getBodyLocation() {
return bodyLocation;
}
public void setBodyLocation(Integer bodyLocation) {
Integer oldValue = this.bodyLocation;
this.bodyLocation = bodyLocation;
propertySupport.firePropertyChange(PROP_BODYLOCATION, oldValue, bodyLocation);
}
public boolean getIsUnmovable() {
return isUnmovable;
}
public void setIsUnmovable(boolean isUnmovable) {
boolean oldValue = this.isUnmovable;
this.isUnmovable = isUnmovable;
propertySupport.firePropertyChange(PROP_ISUNMOVABLE, oldValue, isUnmovable);
}
public int getAcBonus() {
return acBonus;
}
public void setAcBonus(Integer acBonus) {
Integer oldValue = this.acBonus;
this.acBonus = acBonus;
propertySupport.firePropertyChange(PROP_ACBONUS, oldValue, acBonus);
}
public int getUseTimeDelay() {
return useTimeDelay;
}
public void setUseTimeDelay(Integer useTimeDelay) {
Integer oldValue = this.useTimeDelay;
this.useTimeDelay = useTimeDelay;
propertySupport.firePropertyChange(PROP_USETIMEDELAY, oldValue, useTimeDelay);
}
public int getDamageDice() {
return damageDice;
}
public void setDamageDice(Integer damageDice) {
Integer oldValue = this.damageDice;
this.damageDice = damageDice;
propertySupport.firePropertyChange(PROP_DAMAGEDICE, oldValue, damageDice);
}
public int getDamageDiceSides() {
return damageDiceSides;
}
public void setDamageDiceSides(Integer damageDiceSides) {
Integer oldValue = this.damageDiceSides;
this.damageDiceSides = damageDiceSides;
propertySupport.firePropertyChange(PROP_DAMAGEDICESIDES, oldValue, damageDiceSides);
}
public int getDamageType() {
return damageType;
}
public void setDamageType(Integer damageType) {
Integer oldValue = this.damageType;
this.damageType = damageType;
propertySupport.firePropertyChange(PROP_DAMAGETYPE, oldValue, damageType);
}
public boolean getLightProvided() {
return lightProvided;
}
public void setLightProvided(boolean lightProvided) {
boolean oldValue = this.lightProvided;
this.lightProvided = lightProvided;
propertySupport.firePropertyChange(PROP_LIGHTPROVIDED, oldValue, lightProvided);
}
#Override
public int hashCode() {
int hash = 0;
hash += (itemId != -1 ? itemId.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 Items)) {
return false;
}
Items other = (Items) object;
if ((this.itemId == -1 && other.itemId != -1) || (this.itemId != -1 &&
!((this.itemId) == (other.itemId)))) {
return false;
}
return true;
}
}
THE DATA THAT IS IN THE ITEMS TABLE:
INSERT INTO mit_items (roomid, characterid, storeid, name, description, type, worth, bodylocation, isunmovable, acbonus, useTimeDelay, damageDice, damageDiceSides, damageType, lightprovided) VALUES(1, -1, -1, 'sword', 'plain steel sword', -1, 0.0, -1, false, -1, -1, -1, -1, -1, false);
One interesting thing is that after the exception throws the database shows that the roomId has in fact been set to -1. However the other fields have not been updated. If I reorder the setFields(-1) methods the exception still trigger on the first method. Also, originally the try-catch block was not there. I had to add it in order to see the root cause exception because this method has the #Transactional annotation which wraps the exception in a general RollbackException that does not show the root cause exception.
Thanks, RC that fixed the problem. propertySupport was returning null. Not sure why, it normally has a Long number cast to a String in there. I ended up removing propertySupport from Items.java Entity class which fixed the problem.
I have feeling why it was failing in this case and not others is because I was manually inserting a record in the Items table for testing and I left the propertySupport field null. So apparently if you have propertySupport implemented you cannot update values in a record that has a null propertySupport field, which I guess would only occur if you inserted the data by a means other than the entity bean.
Thanks again RC! – Sam