How to remove data from Arraylist by data id - java

I am having problem in removing data from my arraylist by its id.
I have a books in my arraylist and i want to remove a particular books based on its id.
I tried the below code but my data is not removing.
Please check my code below and suggest a solution for it.
Update
When i calls this method then compiler reads all the below code but it does not removes my data from my arraylist. I am not getting any error.
-------------------
-------------------
public String removebookfrmSession()
{
List<Bookdetails> books = new ArrayList<Bookdetails>();
String bookid = request.getParameter("bkid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (ArrayList) session.get(BillTransactionBooksConstants.BOK);
if ( books == null ) books = new ArrayList<Bookdetails>();
boolean already_exists = false;
for ( Bookdetails b : books )
{
if ( Integer.toString(b.getId()).equals(bookid))
{
already_exists = true;
break;
}
}
if (book != null && already_exists )
{
books.remove(book);
System.out.println("books size"+books.size());
session.put(BillTransactionBooksConstants.BOK,books);
}
return SUCCESS;
}
Bookdetails.java (POJO)
package v.esoft.pojos;
// Generated Nov 5, 2012 9:37:14 PM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Bookdetails generated by hbm2java
*/
#Entity
#Table(name = "bookdetails", catalog = "vbsoftware")
public class Bookdetails implements java.io.Serializable {
private Integer id;
private String isbn;
private String bookTitile;
private String authFirstname;
private String authLastname;
private String editionYear;
private Integer subjectId;
private Integer coverId;
private Integer languageId;
private String publisherName;
private Integer editionId;
private Float price;
private String quantity;
private String description;
private Integer locationId;
private String remarks;
private String img1;
private String img2;
private String videoUrl;
private Integer createrId;
private Date createdDate;
private Integer updateId;
private Date updatedDate;
public Bookdetails() {
}
public Bookdetails(String isbn, String bookTitile, String authFirstname,
String authLastname, String editionYear, Integer subjectId,
Integer coverId, Integer languageId, String publisherName,
Integer editionId, Float price, String quantity,
String description, Integer locationId, String remarks,
String img1, String img2, String videoUrl, Integer createrId,
Date createdDate, Integer updateId, Date updatedDate) {
this.isbn = isbn;
this.bookTitile = bookTitile;
this.authFirstname = authFirstname;
this.authLastname = authLastname;
this.editionYear = editionYear;
this.subjectId = subjectId;
this.coverId = coverId;
this.languageId = languageId;
this.publisherName = publisherName;
this.editionId = editionId;
this.price = price;
this.quantity = quantity;
this.description = description;
this.locationId = locationId;
this.remarks = remarks;
this.img1 = img1;
this.img2 = img2;
this.videoUrl = videoUrl;
this.createrId = createrId;
this.createdDate = createdDate;
this.updateId = updateId;
this.updatedDate = updatedDate;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "isbn", length = 90)
public String getIsbn() {
return this.isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
#Column(name = "book_titile")
public String getBookTitile() {
return this.bookTitile;
}
public void setBookTitile(String bookTitile) {
this.bookTitile = bookTitile;
}
#Column(name = "auth_firstname", length = 120)
public String getAuthFirstname() {
return this.authFirstname;
}
public void setAuthFirstname(String authFirstname) {
this.authFirstname = authFirstname;
}
#Column(name = "auth_lastname", length = 120)
public String getAuthLastname() {
return this.authLastname;
}
public void setAuthLastname(String authLastname) {
this.authLastname = authLastname;
}
#Column(name = "edition_year", length = 20)
public String getEditionYear() {
return this.editionYear;
}
public void setEditionYear(String editionYear) {
this.editionYear = editionYear;
}
#Column(name = "subject_id")
public Integer getSubjectId() {
return this.subjectId;
}
public void setSubjectId(Integer subjectId) {
this.subjectId = subjectId;
}
#Column(name = "cover_id")
public Integer getCoverId() {
return this.coverId;
}
public void setCoverId(Integer coverId) {
this.coverId = coverId;
}
#Column(name = "language_id")
public Integer getLanguageId() {
return this.languageId;
}
public void setLanguageId(Integer languageId) {
this.languageId = languageId;
}
#Column(name = "publisher_name", length = 70)
public String getPublisherName() {
return this.publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
#Column(name = "edition_id")
public Integer getEditionId() {
return this.editionId;
}
public void setEditionId(Integer editionId) {
this.editionId = editionId;
}
#Column(name = "price", precision = 12, scale = 0)
public Float getPrice() {
return this.price;
}
public void setPrice(Float price) {
this.price = price;
}
#Column(name = "quantity", length = 40)
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Column(name = "description", length = 65535)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "location_id")
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
#Column(name = "remarks", length = 65535)
public String getRemarks() {
return this.remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
#Column(name = "img1")
public String getImg1() {
return this.img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
#Column(name = "img2")
public String getImg2() {
return this.img2;
}
public void setImg2(String img2) {
this.img2 = img2;
}
#Column(name = "video_url", length = 65535)
public String getVideoUrl() {
return this.videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
#Column(name = "creater_id")
public Integer getCreaterId() {
return this.createrId;
}
public void setCreaterId(Integer createrId) {
this.createrId = createrId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", length = 19)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Column(name = "update_id")
public Integer getUpdateId() {
return this.updateId;
}
public void setUpdateId(Integer updateId) {
this.updateId = updateId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_date", length = 19)
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
}

Your Bookdetails class must implement the public boolean equals(Object o) method in order to use the List#remove(Object o) method. Otherwise, you should handle the object removal by yourself as stated by #juergend.
Implementing the equals method would be like this:
public class Bookdetails {
private int id;
//other attributes and methods...
#Override
public boolean equals(Object o) {
if (o instanceof Bookdetails) {
Bookdetails oBookdetails = (Bookdetails)o;
return (this.id == oBookdetails.id);
}
return false;
}
}
Now the books.remove(book); would work without need of the for ( Bookdetails b : books ) loop.

Default equality is based on reference so you need to assign book to reference from the list so that remove will work. Or you can override equals but I am not quite sure whether you can provide equality on bookId
for ( Bookdetails b : books )
{
if ( Integer.toString(b.getId()).equals(bookid))
{
already_exists = true;
book= b;
break;
}
}
Then when you call remove because of reference equality it will remove book
Update:
If its POJO and you have primary key then you can easily implement equals on primary key that is id. No need to iterate over the list.

Related

Why my servicelaundry_id didn't insert on the table <Hibernate | Spring Boot>

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

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

I am using Spring Boot 2.7.2 , Java/JDK 18.
Entity
#Entity
#Table(name = "account")
public class Account {
#EmbeddedId
private AccountId id;
#MapsId("tenantId")
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "tenant_id", nullable = false)
private Tenant tenant;
#Column(name = "account_number", nullable = false, length = 32)
private String accountNumber;
#Column(name = "account_name", nullable = false, length = 128)
private String accountName;
#Column(name = "account_name_english", length = 128)
private String accountNameEnglish;
#Column(name = "account_name_chinese", length = 128)
private String accountNameChinese;
#Column(name = "account_name_korean", length = 128)
private String accountNameKorean;
#Column(name = "description", length = 512)
private String description;
#Column(name = "parent_id")
private Integer parentId;
#Column(name = "bkit_code_id", length = 128)
private String bkitCodeId;
#Column(name = "grade")
private Integer grade;
#Column(name = "is_parent", nullable = false)
private Boolean isParent = false;
#Column(name = "account_category_kind", nullable = false)
private Integer accountCategoryKind;
#Column(name = "is_postable_in_foreign_currency", nullable = false)
private Boolean isPostableInForeignCurrency = false;
#Column(name = "detail_by_account_object", nullable = false)
private Boolean detailByAccountObject = false;
#Column(name = "account_object_type")
private Integer accountObjectType;
#Column(name = "detail_by_bank_account", nullable = false)
private Boolean detailByBankAccount = false;
#Column(name = "detail_by_job", nullable = false)
private Boolean detailByJob = false;
#Column(name = "detail_by_job_kind")
private Integer detailByJobKind;
#Column(name = "detail_by_project_work", nullable = false)
private Boolean detailByProjectWork = false;
#Column(name = "detail_by_project_work_kind")
private Integer detailByProjectWorkKind;
#Column(name = "detail_by_order", nullable = false)
private Boolean detailByOrder = false;
#Column(name = "detail_by_order_kind")
private Integer detailByOrderKind;
#Column(name = "detail_by_contract", nullable = false)
private Boolean detailByContract = false;
#Column(name = "detail_by_contract_kind")
private Integer detailByContractKind;
#Column(name = "detail_by_expense_item", nullable = false)
private Boolean detailByExpenseItem = false;
#Column(name = "detail_by_expense_item_kind")
private Integer detailByExpenseItemKind;
#Column(name = "detail_by_department", nullable = false)
private Boolean detailByDepartment = false;
#Column(name = "detail_by_department_kind")
private Integer detailByDepartmentKind;
#Column(name = "detail_by_list_item", nullable = false)
private Boolean detailByListItem = false;
#Column(name = "detail_by_list_item_kind")
private Integer detailByListItemKind;
#Column(name = "active_status", nullable = false)
private Boolean activeStatus = false;
#Column(name = "created")
private OffsetDateTime created;
#Column(name = "created_by", length = 64)
private String createdBy;
#Column(name = "modified")
private OffsetDateTime modified;
#Column(name = "modified_by", length = 64)
private String modifiedBy;
#Column(name = "sort_bkit_code_id", length = 128)
private String sortBkitCodeId;
#Column(name = "detail_by_pu_contract", nullable = false)
private Boolean detailByPuContract = false;
#Column(name = "detail_by_pu_contract_kind")
private Integer detailByPuContractKind;
public AccountId getId() {
return id;
}
public void setId(AccountId id) {
this.id = id;
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountNameEnglish() {
return accountNameEnglish;
}
public void setAccountNameEnglish(String accountNameEnglish) {
this.accountNameEnglish = accountNameEnglish;
}
public String getAccountNameChinese() {
return accountNameChinese;
}
public void setAccountNameChinese(String accountNameChinese) {
this.accountNameChinese = accountNameChinese;
}
public String getAccountNameKorean() {
return accountNameKorean;
}
public void setAccountNameKorean(String accountNameKorean) {
this.accountNameKorean = accountNameKorean;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getBkitCodeId() {
return bkitCodeId;
}
public void setBkitCodeId(String bkitCodeId) {
this.bkitCodeId = bkitCodeId;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Boolean getIsParent() {
return isParent;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
public Integer getAccountCategoryKind() {
return accountCategoryKind;
}
public void setAccountCategoryKind(Integer accountCategoryKind) {
this.accountCategoryKind = accountCategoryKind;
}
public Boolean getIsPostableInForeignCurrency() {
return isPostableInForeignCurrency;
}
public void setIsPostableInForeignCurrency(Boolean isPostableInForeignCurrency) {
this.isPostableInForeignCurrency = isPostableInForeignCurrency;
}
public Boolean getDetailByAccountObject() {
return detailByAccountObject;
}
public void setDetailByAccountObject(Boolean detailByAccountObject) {
this.detailByAccountObject = detailByAccountObject;
}
public Integer getAccountObjectType() {
return accountObjectType;
}
public void setAccountObjectType(Integer accountObjectType) {
this.accountObjectType = accountObjectType;
}
public Boolean getDetailByBankAccount() {
return detailByBankAccount;
}
public void setDetailByBankAccount(Boolean detailByBankAccount) {
this.detailByBankAccount = detailByBankAccount;
}
public Boolean getDetailByJob() {
return detailByJob;
}
public void setDetailByJob(Boolean detailByJob) {
this.detailByJob = detailByJob;
}
public Integer getDetailByJobKind() {
return detailByJobKind;
}
public void setDetailByJobKind(Integer detailByJobKind) {
this.detailByJobKind = detailByJobKind;
}
public Boolean getDetailByProjectWork() {
return detailByProjectWork;
}
public void setDetailByProjectWork(Boolean detailByProjectWork) {
this.detailByProjectWork = detailByProjectWork;
}
public Integer getDetailByProjectWorkKind() {
return detailByProjectWorkKind;
}
public void setDetailByProjectWorkKind(Integer detailByProjectWorkKind) {
this.detailByProjectWorkKind = detailByProjectWorkKind;
}
public Boolean getDetailByOrder() {
return detailByOrder;
}
public void setDetailByOrder(Boolean detailByOrder) {
this.detailByOrder = detailByOrder;
}
public Integer getDetailByOrderKind() {
return detailByOrderKind;
}
public void setDetailByOrderKind(Integer detailByOrderKind) {
this.detailByOrderKind = detailByOrderKind;
}
public Boolean getDetailByContract() {
return detailByContract;
}
public void setDetailByContract(Boolean detailByContract) {
this.detailByContract = detailByContract;
}
public Integer getDetailByContractKind() {
return detailByContractKind;
}
public void setDetailByContractKind(Integer detailByContractKind) {
this.detailByContractKind = detailByContractKind;
}
public Boolean getDetailByExpenseItem() {
return detailByExpenseItem;
}
public void setDetailByExpenseItem(Boolean detailByExpenseItem) {
this.detailByExpenseItem = detailByExpenseItem;
}
public Integer getDetailByExpenseItemKind() {
return detailByExpenseItemKind;
}
public void setDetailByExpenseItemKind(Integer detailByExpenseItemKind) {
this.detailByExpenseItemKind = detailByExpenseItemKind;
}
public Boolean getDetailByDepartment() {
return detailByDepartment;
}
public void setDetailByDepartment(Boolean detailByDepartment) {
this.detailByDepartment = detailByDepartment;
}
public Integer getDetailByDepartmentKind() {
return detailByDepartmentKind;
}
public void setDetailByDepartmentKind(Integer detailByDepartmentKind) {
this.detailByDepartmentKind = detailByDepartmentKind;
}
public Boolean getDetailByListItem() {
return detailByListItem;
}
public void setDetailByListItem(Boolean detailByListItem) {
this.detailByListItem = detailByListItem;
}
public Integer getDetailByListItemKind() {
return detailByListItemKind;
}
public void setDetailByListItemKind(Integer detailByListItemKind) {
this.detailByListItemKind = detailByListItemKind;
}
public Boolean getActiveStatus() {
return activeStatus;
}
public void setActiveStatus(Boolean activeStatus) {
this.activeStatus = activeStatus;
}
public OffsetDateTime getCreated() {
return created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public OffsetDateTime getModified() {
return modified;
}
public void setModified(OffsetDateTime modified) {
this.modified = modified;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public String getSortBkitCodeId() {
return sortBkitCodeId;
}
public void setSortBkitCodeId(String sortBkitCodeId) {
this.sortBkitCodeId = sortBkitCodeId;
}
public Boolean getDetailByPuContract() {
return detailByPuContract;
}
public void setDetailByPuContract(Boolean detailByPuContract) {
this.detailByPuContract = detailByPuContract;
}
public Integer getDetailByPuContractKind() {
return detailByPuContractKind;
}
public void setDetailByPuContractKind(Integer detailByPuContractKind) {
this.detailByPuContractKind = detailByPuContractKind;
}
}
#Embeddable
public class AccountId implements Serializable {
private static final long serialVersionUID = 2728412978200770912L;
#Column(name = "id", nullable = false)
private Integer id;
#Column(name = "tenant_id", nullable = false)
private Integer tenantId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTenantId() {
return tenantId;
}
public void setTenantId(Integer tenantId) {
this.tenantId = tenantId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
AccountId entity = (AccountId) o;
return Objects.equals(this.tenantId, entity.tenantId) &&
Objects.equals(this.id, entity.id);
}
#Override
public int hashCode() {
return Objects.hash(tenantId, id);
}
}
My services
public interface AccountService {
// FIXME: Need get Account belong to tenant_id .
List<Account> getAll();
}
and
#Service
public class AccountServiceImpl implements AccountService {
#Autowired
AccountRepository accountRepository;
// FIXME: Need get Account belong to tenant_id .
#Override
public List<Account> getAll() {
return accountRepository.findAll(); // <-- Need revise.
}
}
How to find all accounts by a tenant_id? I can use native SQL query, but I want use Spring Data JPA API more than.
You can use Spring Data Repository query keywords on your composite key by find all accounts by following code.
#Repository
public interface AccountRepository extends JpaRepository<Account, AccountId> {
List<Account> findAllByTenantId(Integer tenant_id);
}

why i can not convert JSON (GSON) date format to java object from retrofit request body?

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

#ElementCollection does not getting detached

My goal is to clone entity 'Product' with all its filters.
For example, I have an entity (getters and setters omitted for simplicity):
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ElementCollection()
private List<Filter> filters = new ArrayList<Filter>();
}
And embeddable class:
#Embeddable
public class Filter {
#Column(length = 255, nullable = false)
private String name;
#Column(nullable = false)
private long variant = -1;
}
Now, if I do:
entityManager.detach(product);
product.setId(null);
productService.save(product);
I will get a copy of product entity but with filters from original product. In meanwhile original product will end up with no filters at all..
Thats how filter's table rows looks like:
Before:
product_id; name; variant
217; "f2"; 86
After:
product_id; name; variant
218; "f2"; 86
I tried detach each filter from the list but it gives me error.
How can I make it copy filters with an entity?
Edit: Added full Product and Filter code:
package com.serhiy1.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.SortableField;
import org.joda.time.DateTime;
import com.serhiy1.constraint.LocalePacker;
#Indexed
#Entity
#EntityListeners(ProductListener.class)
public class Product {
public static final int PRICE_PER_ONE = 0;
public static final int PRICE_PER_METER = 1;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long code;
private String name = "";
private String grouping = "";
#Field
#Column(columnDefinition="text")
private String title = "";
#Field
#Column(columnDefinition="text")
private String intro = "";
#Column(columnDefinition="text")
private String content = "";
#Field
#Column(columnDefinition="text")
private String contentHtml = "";
private String locale = "en";
private Long parentId = 0L;
private DateTime time;
private DateTime timeMod;
private Long balanceRequired = 0L;
private Integer index = 0;
#Field(name = "price_sort")
#SortableField(forField = "price_sort")
private Double price = 0.0;
private Integer pricePer;
#Transient
private long childrenCount = 0;
#Transient
private String image = "";
#Transient
private List<String> images = new ArrayList<String>();
#ManyToOne(targetEntity = User.class)
#JoinColumn(nullable = false, name = "user_id")
#LazyCollection(LazyCollectionOption.FALSE)
private User user;
#ManyToOne(targetEntity = Product.class)
#JoinColumn(nullable = true, name = "category_id")
#LazyCollection(LazyCollectionOption.FALSE)
private Product category;
#ElementCollection()
private List<Filter> filters = new ArrayList<Filter>();
#ElementCollection()
private List<Modifier> modifiers = new ArrayList<Modifier>();
public Product() {
}
#Transient
private String _title = "";
#Transient
private String _intro = "";
#Transient
private String _content = "";
#Transient
private String _contentHtml = "";
public void pack(String locale, List<String> locales) {
if(locale.contains("_")) return;
title = LocalePacker.repack(locale, _title, title, locales);
intro = LocalePacker.repack(locale, _intro, intro, locales);
content = LocalePacker.repack(locale, _content, content, locales);
contentHtml = LocalePacker.repack(locale, _contentHtml, contentHtml, locales);
}
public void unpack(String locale) {
_title = LocalePacker.unpackStr(locale, title).getOrDefault(locale, "");
_intro = LocalePacker.unpackStr(locale, intro).getOrDefault(locale, "");
_content = LocalePacker.unpackStr(locale, content).getOrDefault(locale, "");
_contentHtml = LocalePacker.unpackStr(locale, contentHtml).getOrDefault(locale, "");
}
public void copy(String landFrom, String landTo) {
title = LocalePacker.copyLang(title, landFrom, landTo);
intro = LocalePacker.copyLang(intro, landFrom, landTo);
content = LocalePacker.copyLang(content, landFrom, landTo);
contentHtml = LocalePacker.copyLang(contentHtml, landFrom, landTo);
}
public Modifier getModifier(String name) {
for(Modifier m: modifiers) {
if(m.getName().equals(name)) return m;
}
return null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getCode() {
return code == null ? id : code;
}
public void setCode(long code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrouping() {
return grouping;
}
public void setGrouping(String grouping) {
this.grouping = grouping;
}
public String getTitle() {
return _title;
}
public void setTitle(String title) {
this._title = title;
}
public String getIntro() {
return _intro;
}
public void setIntro(String intro) {
this._intro = intro;
}
public String getContent() {
return _content;
}
public void setContent(String content) {
this._content = content;
}
public String getContentHtml() {
return _contentHtml;
}
public void setContentHtml(String contentHtml) {
this._contentHtml = contentHtml;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public DateTime getTime() {
return time;
}
public void setTime(DateTime time) {
this.time = time;
}
public DateTime getTimeMod() {
return timeMod;
}
public void setTimeMod(DateTime timeMod) {
this.timeMod = timeMod;
}
public long getBalanceRequired() {
return balanceRequired == null ? 0L : balanceRequired;
}
public void setBalanceRequired(long balanceRequired) {
this.balanceRequired = balanceRequired;
}
public Integer getIndex() {
//return index == null ? 1000 : index;
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public double getPrice() {
return price == null ? 0.0 : price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPricePer() {
return pricePer == null ? PRICE_PER_METER : pricePer;
}
public void setPricePer(int pricePer) {
this.pricePer = pricePer;
}
public long getChildrenCount() {
return childrenCount;
}
public void setChildrenCount(long childrenCount) {
this.childrenCount = childrenCount;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Product getCategory() {
return category;
}
public void setCategory(Product category) {
this.category = category;
}
public List<Filter> getFilters() {
return filters;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
public List<Modifier> getModifiers() {
return modifiers;
}
public void setModifiers(List<Modifier> modifiers) {
this.modifiers = modifiers;
}
public boolean isCategory() { return price < 0; }
#Override
public String toString() {
return "Article{" +
"id=" + id +
'}';
}
}
..
package com.serhiy1.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Transient;
#Embeddable
public class Filter {
#Column(length = 255, nullable = false)
private String name;
#Column(nullable = false)
private long variant = -1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getVariant() {
return variant;
}
public void setVariant(long variant) {
this.variant = variant;
}
}
I made a mini project trying to replicate your issue.
It is a String Boot project with H2 database and JPA (Hibernate implementation).
On startup, Hibernate creates 2 tables:
create table product (
id bigint not null,
primary key (id)
)
and
create table product_filters (
product_id bigint not null,
name varchar(255) not null,
variant bigint not null
)
On product with filters creation, both tables get inserted:
insert
into
product
(id)
values
(1)
and
insert
into
product_filters
(product_id, name, variant)
values
(1, "f1", 1)
After:
entityManager.detach(product);
product.setId(null);
productService.save(product);
Hibernate issues:
delete
from
product_filters
where
product_id=1
which is normal, since filters is an ElementCollection therefore it is totally owned by the entity Product. On productService.save(product) Hibernate detects that filters collection is bound to another Product therefore deletes the old bound (from product_filter table) before creating a new one.
The only way to overcome the deletion is to recreate the collection:
List<Filter> filters = new ArrayList<Filter>();
filters.addAll(oldFilters);
product.setFilters(filters);
To sum up, here is the solution:
// To trigger the fetch
List<Filter> filters = new ArrayList<Filter>(product.getFilters());
entityManager.detach(product);
product.setId(null);
product.setFilters(filters);
productService.save(product);

org.hibernate.QueryException: could not resolve property: MetadataForHibernate of: bookshare.entity.hasbooks.HasBooks

this is the first time I'm working with Hibernate and I want to make this simple query in Hibernate: sql query
I've tried every thing but every time I get the same error output:
org.hibernate.QueryException: could not resolve property: MetadataForHibernate of: bookshare.entity.hasbooks.HasBooks [SELECT H.MetadataForHibernate FROM
Function I made:
#SuppressWarnings("unchecked")
public List<MetadataForHibernate> getBooksByTitle(int userID, String Title) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(
"SELECT H.MetadataForHibernate FROM HasBooks as H WHERE H.users.id = :userid AND LOWER(H.MetadataForHibernate.title) LIKE LOWER(:title) ORDER BY B.title ASC ");
query.setParameter("userid", userID);
query.setParameter("title", "%" + Title + "%");
List<MetadataForHibernate> books = (List<MetadataForHibernate>) query.list();
tx.rollback();
session.close();
factory.close();
return books;
}
MetadataForHibernate:
#Entity
#Table(name="tblbooks")
public class MetadataForHibernate {
#Id
#Column(name = "bookshareId")
private int bookshareId;
#Column(name="author")
private String author;
#Column(name = "availableToDownload")
private int availableToDownload;
#Column(name = "briefSynopsis")
private String briefSynopsis;
#Column(name="category")
private String category;
#Column(name = "completeSynopsis")
private String completeSynopsis;
#Column(name = "contentId")
private int contentId;
#Column(name = "copyright")
private Date copyright;
#Column(name="downloadFormat")
private String downloadFormat;
#Column(name="dtbookSize")
private int dtbookSize;
#Column(name = "freelyAvailable")
private int freelyAvailable;
#Column(name = "brf")
private int brf;
#Column(name = "daisy")
private int daisy;
#Column(name = "images")
private int images;
#Column(name = "isbn13")
private String isbn13;
#Column(name="language")
private String language;
#Column(name = "publishDate")
private Date publishDate;
#Column(name = "publisher")
private String publisher;
#Column(name = "quality")
private String quality;
#Column(name = "title")
private String title;
#OneToMany(mappedBy="book")
private List<HasBooks> hasBooks;
public MetadataForHibernate(){
hasBooks = new ArrayList<HasBooks>();
}
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getFreelyAvailable ()
{
return freelyAvailable;
}
public void setFreelyAvailable (String freelyAvailable)
{
this.freelyAvailable = Integer.parseInt(freelyAvailable);
}
public String getCompleteSynopsis ()
{
return completeSynopsis;
}
public void setCompleteSynopsis (String completeSynopsis)
{
this.completeSynopsis = completeSynopsis;
}
public int getDaisy ()
{
return daisy;
}
public void setDaisy (String daisy)
{
this.daisy = Integer.parseInt(daisy);
}
public Date getCopyright ()
{
return copyright;
}
public void setCopyright (Date copyright)
{
this.copyright = copyright;
}
public int getAvailableToDownload ()
{
return availableToDownload;
}
public void setAvailableToDownload (String availableToDownload)
{
this.availableToDownload = Integer.parseInt(availableToDownload);
}
public int getContentId ()
{
return contentId;
}
public void setContentId (String contentId)
{
this.contentId = Integer.parseInt(contentId);
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public int getBookshareId ()
{
return bookshareId;
}
public void setBookshareId (String bookshareId)
{
this.bookshareId = Integer.parseInt(bookshareId);
}
public String getAuthor ()
{
return author;
}
public void setAuthor (String author)
{
this.author = author;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getCategory ()
{
return category;
}
public void setCategory (String category)
{
this.category = category;
}
public String getQuality ()
{
return quality;
}
public void setQuality (String quality)
{
this.quality = quality;
}
public String getIsbn13 ()
{
return isbn13;
}
public void setIsbn13 (String isbn13)
{
this.isbn13 = isbn13;
}
public int getImages ()
{
return images;
}
public void setImages (String images)
{
this.images = Integer.parseInt(images);
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getBriefSynopsis ()
{
return briefSynopsis;
}
public void setBriefSynopsis (String briefSynopsis)
{
this.briefSynopsis = briefSynopsis;
}
public int getDtbookSize ()
{
return dtbookSize;
}
public void setDtbookSize (int dtbookSize)
{
this.dtbookSize = dtbookSize;
}
public int getBrf ()
{
return brf;
}
public void setBrf (String brf)
{
this.brf = Integer.parseInt(brf);
}
public Date getPublishDate ()
{
return publishDate;
}
public void setPublishDate (Date publishDate)
{
this.publishDate = publishDate;
}
public String getDownloadFormat ()
{
return downloadFormat;
}
public void setDownloadFormat (String downloadFormat)
{
this.downloadFormat = downloadFormat;
}
#Override
public String toString()
{
return "ClassPojo [freelyAvailable = "+freelyAvailable+", completeSynopsis = "+completeSynopsis+", daisy = "+daisy+", copyright = "+copyright+", availableToDownload = "+availableToDownload+", contentId = "+contentId+", publisher = "+publisher+", bookshareId = "+bookshareId+", author = "+author+", title = "+title+", category = "+category+", quality = "+quality+", isbn13 = "+isbn13+", images = "+images+", language = "+language+", briefSynopsis = "+briefSynopsis+", dtbookSize = "+dtbookSize+", brf = "+brf+", publishDate = "+publishDate+", downloadFormat = "+downloadFormat+"]";
}
public void convertDataOf(BookDetail book) throws ParseException{
DateFormat format;
Date date;
this.bookshareId=book.getBookshare().getBook().getMetadata().getBookshareId();
this.author=String.join(",", book.getBookshare().getBook().getMetadata().getAuthor());
this.availableToDownload=book.getBookshare().getBook().getMetadata().getAvailableToDownload();
this.briefSynopsis=book.getBookshare().getBook().getMetadata().getBriefSynopsis();
this.category=String.join(",", book.getBookshare().getBook().getMetadata().getCategory());
this.completeSynopsis=book.getBookshare().getBook().getMetadata().getCompleteSynopsis();
this.contentId=book.getBookshare().getBook().getMetadata().getContentId();
//convert String to date
format = new SimpleDateFormat("yyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getCopyright());
this.copyright=date;
this.downloadFormat=String.join(",", book.getBookshare().getBook().getMetadata().getDownloadFormat());
this.dtbookSize=book.getBookshare().getBook().getMetadata().getDtbookSize();
this.freelyAvailable=book.getBookshare().getBook().getMetadata().getFreelyAvailable();
this.brf=book.getBookshare().getBook().getMetadata().getBrf();
this.daisy=book.getBookshare().getBook().getMetadata().getDaisy();
this.images=book.getBookshare().getBook().getMetadata().getImages();
this.isbn13=book.getBookshare().getBook().getMetadata().getIsbn13();
this.language=String.join(",", book.getBookshare().getBook().getMetadata().getLanguage());
//convert String to date
format = new SimpleDateFormat("MMddyyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getPublishDate());
this.publishDate=date;
this.publisher=book.getBookshare().getBook().getMetadata().getPublisher();
this.quality=book.getBookshare().getBook().getMetadata().getQuality();
this.title=book.getBookshare().getBook().getMetadata().getTitle();
}
}
HasBooks:
#Entity
#Table(name = "tblhasbooks")
public class HasBooks implements Serializable {
//#Column(name = "Id",unique = true,nullable = false)
#Id
#GeneratedValue()
private int hasBooksId;
#ManyToOne(cascade = CascadeType.ALL)
private Users user;
#ManyToOne(cascade = CascadeType.ALL)
private MetadataForHibernate book;
public MetadataForHibernate getBook() {
return book;
}
public Users getUser() {
return user;
}
public int getHasBooksId() {
return hasBooksId;
}
public void setHasBooksId(int hasBooksId) {
this.hasBooksId = hasBooksId;
}
public void setUser(Users user) {
this.user = user;
}
public void setBook(MetadataForHibernate book) {
this.book = book;
}
}
Users:
#Entity
#Table(name="tblusers")
public class Users implements Serializable{
public Users(){hasBooks = new ArrayList<HasBooks>();
}
#Id
#Column(name = "Id",unique = true,nullable = false)
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#OneToMany(mappedBy="user")
private List<HasBooks> hasBooks;
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getId() {
return Id;
}
public void setUser_id(int Id) {
this.Id = Id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You need to specify a property name, not a property type.
SELECT H.MetadataForHibernate FROM HasBooks as H
need to be corrected to
SELECT H.book FROM HasBooks H
And you need a join to check a book properties
SELECT book
FROM HasBooks H inner join H.book book
where book.title :=title
The query you have written is not valid Hibernate Query Language (HQL), check the documentation for hints, or you can always use a native query to get an Object[] list from the result set, keeping the query you already have.

Categories