New to JPA and encountered an issue.
Basically I am creating this bean:
PurchaseOrderControlBean purchaseOrderControl = new PurchaseOrderControlBean();
and using setters in order to fill it with data.
While trying to persist data to my DB I get this exception:
java.lang.IllegalArgumentException: Object is not a known entity type.
My Entity:
#Entity
#Table(name = "IMS_PURCHASE_ORDER_CONTROL", schema = "IMS")
public class PurchaseOrderControlBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5801211822984821162L;
#Id
#Column(name = "ID")
private BigDecimal id;
#Id
#Column(name = "INSURED_ID")
private BigDecimal insuredId;
#Column(name = "PROCESS_TYPE")
private BigDecimal processType;
#Column(name = "PROCESS_KEY")
private String processKey;
#Column(name = "SUPER_ClLAIM_NUM")
private BigDecimal superClaimNum;
#Column(name = "PURCHASE_ORDER_NUM")
private BigDecimal processOrderNum;
#Column(name = "PURCHASE_ORDER_SERVICE_TYPE")
private BigDecimal PurchaseOrderServiceType;
#Id
#Column(name = "CONTRACTOR_ID")
private BigDecimal Contarctor_Id;
#Column(name = "OPEN_DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date openDate;
#Column(name = "STATUS")
private BigDecimal status;
#Column(name = "EXECUTION_DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date exccutionDate;
#Column(name = "TOTAL_DURATION_DAYS")
private BigDecimal totalDurationDays;
#Column(name = "TOTAL_DELAY_DAYS")
private BigDecimal totalDelayDays;
#Id
#Column(name = "UPDATE_USER_ID")
private BigDecimal updateUserId;
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public BigDecimal getInsuredId() {
return insuredId;
}
public void setInsuredId(BigDecimal bigDecimal) {
this.insuredId = bigDecimal;
}
public BigDecimal getProcessType() {
return processType;
}
public void setProcessType(BigDecimal processType) {
this.processType = processType;
}
public String getProcessKey() {
return processKey;
}
public void setProcessKey(String processKey) {
this.processKey = processKey;
}
public BigDecimal getSuperClaimNum() {
return superClaimNum;
}
public void setSuperClaimNum(BigDecimal superClaimNum) {
this.superClaimNum = superClaimNum;
}
public BigDecimal getProcessOrderNum() {
return processOrderNum;
}
public void setProcessOrderNum(BigDecimal processOrderNum) {
this.processOrderNum = processOrderNum;
}
public BigDecimal getPurchaseOrderServiceType() {
return PurchaseOrderServiceType;
}
public void setPurchaseOrderServiceType(BigDecimal purchaseOrderServiceType) {
PurchaseOrderServiceType = purchaseOrderServiceType;
}
public BigDecimal getContarctor_Id() {
return Contarctor_Id;
}
public void setContarctor_Id(BigDecimal contarctor_Id) {
Contarctor_Id = contarctor_Id;
}
public Date getOpenDate() {
return openDate;
}
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
public BigDecimal getStatus() {
return status;
}
public void setStatus(BigDecimal status) {
this.status = status;
}
public Date getExccutionDate() {
return exccutionDate;
}
public void setExccutionDate(Date exccutionDate) {
this.exccutionDate = exccutionDate;
}
public BigDecimal getTotalDurationDays() {
return totalDurationDays;
}
public void setTotalDurationDays(BigDecimal totalDurationDays) {
this.totalDurationDays = totalDurationDays;
}
public BigDecimal getTotalDelayDays() {
return totalDelayDays;
}
public void setTotalDelayDays(BigDecimal totalDelayDays) {
this.totalDelayDays = totalDelayDays;
}
public BigDecimal getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(BigDecimal bigDecimal) {
this.updateUserId = bigDecimal;
}
Persist Method:
public Object save(Object obj) throws TecnicalException {
EntityManager entityManager = null;
EntityTransaction updateTransaction = null;
Object object = null;
boolean success = false;
try {
entityManager = PersistenceUtil.getEntityManager(dbName);
updateTransaction = entityManager.getTransaction();
updateTransaction.begin();
object = entityManager.merge(obj);
success = true;
} catch (PersistenceException e) {
logger.error("Exception while trying to update object " + obj, e);
ErrorLogUtil.writeErrorLog(Application.PERSISTANCE, "mng", null, "BaseDAO-Exception while trying to update object " + obj, "");
throw new TecnicalException(e);
} finally {
if (success) {
try {
updateTransaction.commit();
} catch (Exception e) {
logger.error("Failed commit" + e);
throw new TecnicalException(e);
}
} else {
if (updateTransaction != null && updateTransaction.isActive()) {
updateTransaction.rollback();
}
}
if (entityManager != null) {
entityManager.close();
entityManager = null;
}
}
return object;
}
When debugging the exception occurs on
object = entityManager.merge(obj);
I cannot seem to understand what I am missing here.
I could add any more information if needed.
I saw similar issues on other threads, however, it did not help me.
Thanks
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
Already created Rest Api in Spring Boot function which create new order with few variables and also with picture as a Blob and send it to the database.
And i it all works as it should, but right now when I'm trying get this picture as a response from database I'm getting this Blob as a null.
My Controller code is as shown below.
#GetMapping(path = "/getallorders")
public List<OrderAllUsersResponse> getAllOrders() {
List<OrderAllUsersResponse> returnValue = new ArrayList<>();
List<OrderEntity> orders = orderRepostiory.findAllOrders();
ModelMapper modelMapper = new ModelMapper();
for (int i=0; i < orders.size(); i++) {
returnValue.add(modelMapper.map(orders.get(i), OrderAllUsersResponse.class));
}
return returnValue;
}
My Repository code is as shown below.
public interface OrderRepostiory extends JpaRepository<OrderEntity, Long> {
#Query(value = "SELECT * FROM 34671478_opionion.cargo", nativeQuery = true)
List<OrderEntity> findAllOrders();
}
#Entity(name = "cargo")
public class OrderEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(nullable = false)
private String orderId;
#Column(nullable = false)
private String customer;
#Column(nullable = false)
private String loadingCompanyName;
#Column(nullable = false)
private String loadingCity;
#Column(nullable = false)
private String loadingPostcode;
#Column(nullable = false)
private String dateOfLoading;
#Column(nullable = false)
private String unloadingCompanyName;
#Column(nullable = false)
private String unloadingCity;
#Column(nullable = false)
private String unloadingPostcode;
#Column(nullable = false)
private String dateOfUnloading;
#Column(nullable = false)
private Double nettoPrice;
#Column(nullable = false)
private Double bruttoPrice;
#Column(nullable = false)
private String information;
#Column(nullable = false)
private Boolean paymentStatus = false;
#ManyToOne
#NotFound(action= NotFoundAction.IGNORE)
#JoinColumn(name = "company_id")
private CompanyEntity companyDetails;
#Lob
#Column(name = "photo", columnDefinition="BLOB")
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getLoadingCompanyName() {
return loadingCompanyName;
}
public void setLoadingCompanyName(String loadingCompanyName) {
this.loadingCompanyName = loadingCompanyName;
}
public String getLoadingCity() {
return loadingCity;
}
public void setLoadingCity(String loadingCity) {
this.loadingCity = loadingCity;
}
public String getLoadingPostcode() {
return loadingPostcode;
}
public void setLoadingPostcode(String loadingPostcode) {
this.loadingPostcode = loadingPostcode;
}
public String getDateOfLoading() {
return dateOfLoading;
}
public void setDateOfLoading(String dateOfLoading) {
this.dateOfLoading = dateOfLoading;
}
public String getUnloadingCompanyName() {
return unloadingCompanyName;
}
public void setUnloadingCompanyName(String unloadingCompanyName) {
this.unloadingCompanyName = unloadingCompanyName;
}
public String getUnloadingCity() {
return unloadingCity;
}
public void setUnloadingCity(String unloadingCity) {
this.unloadingCity = unloadingCity;
}
public String getUnloadingPostcode() {
return unloadingPostcode;
}
public void setUnloadingPostcode(String unloadingPostcode) {
this.unloadingPostcode = unloadingPostcode;
}
public String getDateOfUnloading() {
return dateOfUnloading;
}
public void setDateOfUnloading(String dateOfUnloading) {
this.dateOfUnloading = dateOfUnloading;
}
public Double getNettoPrice() {
return nettoPrice;
}
public void setNettoPrice(Double nettoPrice) {
this.nettoPrice = nettoPrice;
}
public Double getBruttoPrice() {
return bruttoPrice;
}
public void setBruttoPrice(Double bruttoPrice) {
this.bruttoPrice = bruttoPrice;
}
public CompanyEntity getCompanyDetails() {
return companyDetails;
}
public void setCompanyDetails(CompanyEntity companyDetails) {
this.companyDetails = companyDetails;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
public Boolean getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Boolean paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
}
Below I show you how response result like from Postman.
As u can see the variable 'photo' is as a null. How can i fix it to get it as a for example byte64string
Below is OrderAllUsersResponse class code:
For modelMapper's default mapping mechanism, your source (OrderEntity) and destination (OrderAllUsersResponse) objects should be similar to each other.
#Entity(name = "cargo")
public class OrderEntity implements Serializable {
#Lob
#Column(name = "photo", columnDefinition="BLOB")
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
and
import com.fasterxml.jackson.annotation.JsonProperty;
public class OrderAllUsersResponse {
#JsonProperty("photo")
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
If the source field name is different from the destination field name then to define property mappings, you will use ModelMapper's TypeMap.
#Entity(name = "cargo")
public class OrderEntity implements Serializable {
#Lob
#Column(name = "photo", columnDefinition="BLOB")
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
and
public class OrderAllUsersResponse {
private byte[] photo;
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
}
TypeMaping
#GetMapping(path = "/getallorders")
public List<OrderAllUsersResponse> getAllOrders() {
List<OrderAllUsersResponse> returnValue = new ArrayList<>();
List<OrderEntity> orders = orderRepostiory.findAllOrders();
ModelMapper modelMapper = new ModelMapper();
TypeMap<OrderEntity, OrderAllUsersResponse> propertyMapper = modelMapper.createTypeMap(OrderEntity.class, OrderAllUsersResponse.class);
for (int i=0; i < orders.size(); i++) {
propertyMapper.addMapping(OrderEntity::getData, OrderAllUsersResponse::setPhoto);
returnValue.add(modelMapper.map(orders.get(i), OrderAllUsersResponse.class));
}
return returnValue;
}
I am sending request body to server (backed by JAVA/JERSEY/JACKSON) from Android (Retrofit). I im logging request body through interceptor and it looks like something
{"workId":"456655","workName":"some work","workOrderDate":"Jan 29, 2020 12:00:00 AM"}
On server side My Project object is able to parse every field except "workOrderDate". I tried to change Gson date format of various type using
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd")
.create();
but still in JSON the format is unchanged (Jan 29, 2020 12:00:00 AM) and it is not assigning to "workOrderDate"field of Project object on server side.
Object on Servier side-
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "project_id")
private Integer projectId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 200)
#Column(name = "work_name")
private String workName;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 2147483647)
#Column(name = "work_description")
private String workDescription;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "consignee_work_order")
private String consigneeWorkOrder;
#Basic(optional = false)
#NotNull
#Column(name = "work_order_date")
#Temporal(TemporalType.DATE)
private Date workOrderDate;
#Size(max = 45)
#Column(name = "consignee")
private String consignee;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "sent_by")
private String sentBy;
#Size(max = 45)
#Column(name = "chargeable_head")
private String chargeableHead;
#Size(max = 45)
#Column(name = "account_unit")
private String accountUnit;
#Size(max = 45)
#Column(name = "fund_exist")
private String fundExist;
#Size(max = 45)
#Column(name = "fund_certificate")
private String fundCertificate;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "approx_cost")
private Double approxCost;
#Column(name = "approx_weight")
private Double approxWeight;
#Size(max = 200)
#Column(name = "drawing")
private String drawing;
#Size(max = 45)
#Column(name = "required_at")
private String requiredAt;
#Lob
#Size(max = 2147483647)
#Column(name = "remark1")
private String remark1;
#Lob
#Size(max = 2147483647)
#Column(name = "remark2")
private String remark2;
#Lob
#Size(max = 2147483647)
#Column(name = "remark3")
private String remark3;
#JoinColumn(name = "division", referencedColumnName = "division_id")
#ManyToOne(optional = false)
private Division division;
public Project() {
}
public Project(Integer projectId) {
this.projectId = projectId;
}
public Project(Integer projectId, String workName, String workDescription, String consigneeWorkOrder, Date workOrderDate, String sentBy) {
this.projectId = projectId;
this.workName = workName;
this.workDescription = workDescription;
this.consigneeWorkOrder = consigneeWorkOrder;
this.workOrderDate = workOrderDate;
this.sentBy = sentBy;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public String getWorkName() {
return workName;
}
public void setWorkName(String workName) {
this.workName = workName;
}
public String getWorkDescription() {
return workDescription;
}
public void setWorkDescription(String workDescription) {
this.workDescription = workDescription;
}
public String getConsigneeWorkOrder() {
return consigneeWorkOrder;
}
public void setConsigneeWorkOrder(String consigneeWorkOrder) {
this.consigneeWorkOrder = consigneeWorkOrder;
}
public Date getWorkOrderDate() {
return workOrderDate;
}
public void setWorkOrderDate(Date workOrderDate) {
this.workOrderDate = workOrderDate;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getSentBy() {
return sentBy;
}
public void setSentBy(String sentBy) {
this.sentBy = sentBy;
}
public String getChargeableHead() {
return chargeableHead;
}
public void setChargeableHead(String chargeableHead) {
this.chargeableHead = chargeableHead;
}
public String getAccountUnit() {
return accountUnit;
}
public void setAccountUnit(String accountUnit) {
this.accountUnit = accountUnit;
}
public String getFundExist() {
return fundExist;
}
public void setFundExist(String fundExist) {
this.fundExist = fundExist;
}
public String getFundCertificate() {
return fundCertificate;
}
public void setFundCertificate(String fundCertificate) {
this.fundCertificate = fundCertificate;
}
public Double getApproxCost() {
return approxCost;
}
public void setApproxCost(Double approxCost) {
this.approxCost = approxCost;
}
public Double getApproxWeight() {
return approxWeight;
}
public void setApproxWeight(Double approxWeight) {
this.approxWeight = approxWeight;
}
public String getDrawing() {
return drawing;
}
public void setDrawing(String drawing) {
this.drawing = drawing;
}
public String getRequiredAt() {
return requiredAt;
}
public void setRequiredAt(String requiredAt) {
this.requiredAt = requiredAt;
}
public String getRemark1() {
return remark1;
}
public void setRemark1(String remark1) {
this.remark1 = remark1;
}
public String getRemark2() {
return remark2;
}
public void setRemark2(String remark2) {
this.remark2 = remark2;
}
public String getRemark3() {
return remark3;
}
public void setRemark3(String remark3) {
this.remark3 = remark3;
}
public Division getDivision() {
return division;
}
public void setDivision(Division division) {
this.division = division;
}
#Override
public int hashCode() {
int hash = 0;
hash += (projectId != null ? projectId.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 Project)) {
return false;
}
Project other = (Project) object;
if ((this.projectId == null && other.projectId != null) || (this.projectId != null && !this.projectId.equals(other.projectId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.nrbwlko.officeprojectmaven1.Project[ projectId=" + projectId + " ]";
}
}
Android side
public class PojoProject {
private Integer projectId;
private String workName;
private String workDescription;
private String consigneeWorkOrder;
private Date workOrderDate;
private String consignee;
private String sentBy;
private String chargeableHead;
private String accountUnit;
private String fundExist;
private String fundCertificate;
private Double approxCost;
private Double approxWeight;
private String drawing;
private String requiredAt;
private String remark1;
private String remark2;
private String remark3;
private PojoDivision division;
public PojoProject(String workName, String workDescription, String consigneeWorkOrder, Date workOrderDate, String consignee, String sentBy, String chargeableHead, String accountUnit, PojoDivision division) {
this.workName = workName;
this.workDescription = workDescription;
this.consigneeWorkOrder = consigneeWorkOrder;
this.workOrderDate = workOrderDate;
this.consignee = consignee;
this.sentBy = sentBy;
this.chargeableHead = chargeableHead;
this.accountUnit = accountUnit;
this.division = division;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public String getWorkName() {
return workName;
}
public void setWorkName(String workName) {
this.workName = workName;
}
public String getWorkDescription() {
return workDescription;
}
public void setWorkDescription(String workDescription) {
this.workDescription = workDescription;
}
public String getConsigneeWorkOrder() {
return consigneeWorkOrder;
}
public void setConsigneeWorkOrder(String consigneeWorkOrder) {
this.consigneeWorkOrder = consigneeWorkOrder;
}
public Date getWorkOrderDate() {
return workOrderDate;
}
public void setWorkOrderDate(Date workOrderDate) {
this.workOrderDate = workOrderDate;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getSentBy() {
return sentBy;
}
public void setSentBy(String sentBy) {
this.sentBy = sentBy;
}
public String getChargeableHead() {
return chargeableHead;
}
public void setChargeableHead(String chargeableHead) {
this.chargeableHead = chargeableHead;
}
public String getAccountUnit() {
return accountUnit;
}
public void setAccountUnit(String accountUnit) {
this.accountUnit = accountUnit;
}
public String getFundExist() {
return fundExist;
}
public void setFundExist(String fundExist) {
this.fundExist = fundExist;
}
public String getFundCertificate() {
return fundCertificate;
}
public void setFundCertificate(String fundCertificate) {
this.fundCertificate = fundCertificate;
}
public Double getApproxCost() {
return approxCost;
}
public void setApproxCost(Double approxCost) {
this.approxCost = approxCost;
}
public Double getApproxWeight() {
return approxWeight;
}
public void setApproxWeight(Double approxWeight) {
this.approxWeight = approxWeight;
}
public String getDrawing() {
return drawing;
}
public void setDrawing(String drawing) {
this.drawing = drawing;
}
public String getRequiredAt() {
return requiredAt;
}
public void setRequiredAt(String requiredAt) {
this.requiredAt = requiredAt;
}
public String getRemark1() {
return remark1;
}
public void setRemark1(String remark1) {
this.remark1 = remark1;
}
public String getRemark2() {
return remark2;
}
public void setRemark2(String remark2) {
this.remark2 = remark2;
}
public String getRemark3() {
return remark3;
}
public void setRemark3(String remark3) {
this.remark3 = remark3;
}
public PojoDivision getDivision() {
return division;
}
public void setDivision(PojoDivision division) {
this.division = division;
}
}
Method to trigger call to server side from ViewModel -
public void save() {
System.out.println(workDate.getValue());
Date workorderDate = getWorkDateFromString(workDate.getValue());
PojoProject project = new PojoProject(workName.getValue(), workDescription.getValue(), workOrder.getValue(), workorderDate, consignee.getValue(), sentBy.getValue(), chargeableHead.getValue(), accountUnit.getValue(), selectedDivision.getValue());
projectRepository.saveProject(project);
}
Here is my serverside Rest End Point where i am collecting JSON into Project() Object and persisting to database --
#POST
#AnnotationSecured
#Path("saveProject")
#Consumes(MediaType.APPLICATION_JSON)
// #Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public void saveNewProject(Project newProject) {
System.out.println("inside save new project");
if (newProject.getWorkOrderDate() == null) {
System.out.println("date is null");
} else {
System.out.println("date is " + newProject.getWorkOrderDate().toString());
}
Project project = null;
EntityManager em = UtilityJPA.getEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.persist(newProject);
transaction.commit();
} catch (Exception ex) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
} finally {
em.clear();
}
}
}
You should try with DateFormat.FULL. It works fine for me like this
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).create();
I have a Hibernate persist on an entity with primary key constructor, but it does not take effect in the database after something I don't know while I need it in some other methods
Here is my code:
Base_Document document = new Base_Document(workItem.getProcessInstanceId());
this.getEntityManager().persist(document);
this.getEntityManager().flush();
this.getEntityManager().close();
and some where else I have :
Object o = this.getEntityManager().find(Base_Document.class,
workItem.getProcessInstanceId());
where o is null. Any help?
my entity code :
#Entity
public class Base_Document implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long processInstanceId;
private DocumentStatus status;
#ManyToOne
private Base_Roles creatorRole;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date createDate;
public Base_Document() {}
public Base_Document(Long processInstanceId) {
this.processInstanceId = processInstanceId;
this.createDate = new Date();
this.status = DocumentStatus.DRAFT;
try {
String currentUser = PublicUtils.getHttpServletRequest().getUserPrincipal().getName();
this.setCreatorRole(PublicUtils.getEntityManager().find(Base_Roles.class, currentUser));
} catch (PolicyContextException ex) {
Logger.getLogger(Base_Document.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Long getId() {
return processInstanceId;
}
public void setId(Long id) {
this.processInstanceId = id;
}
public Long getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(Long processInstanceId) {
this.processInstanceId = processInstanceId;
}
public DocumentStatus getStatus() {
return status;
}
public void setStatus(DocumentStatus status) {
this.status = status;
}
public Base_Roles getCreatorRole() {
return creatorRole;
}
public void setCreatorRole(Base_Roles creatorRole) {
this.creatorRole = creatorRole;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
From Hibernate "persist" description:
However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately
https://access.redhat.com/site/documentation/en-US/JBoss_Enterprise_Web_Platform/5/html/Hibernate_Core_Reference_Guide/objectstate-makingpersistent.html
You can use "save()" if immediately search required.
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.