Api returns blob variable as null - java

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;
}

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

Incorrect auto-generated SQL query in Spring Boot (JPA) CrudRepository

My repository interfaces:
SongsRepository:
public interface SongRepository extends CrudRepository<Song, Integer> {
}
AlbumsRepository
public interface AlbumRepository extends CrudRepository<Album, Integer> {
}
My Model classes:
Album.java
#Entity
#Table(name = "albums", schema = "dbo")
public class Album {
#Id
#GeneratedValue
#Column(name = "album_id")
private Integer albumId;
#Column(name = "album_name")
private String albumName;
#Column(name = "released_by")
private String releasedBy;
#Column(name = "total_duration")
private Integer totalDuration;
#OneToMany(targetEntity = Song.class)
private List<Song> songs;
public Integer getAlbumId() {
return albumId;
}
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
public String getAlbumName() {
return albumName;
}
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
public String getReleasedBy() {
return releasedBy;
}
public void setReleasedBy(String releasedBy) {
this.releasedBy = releasedBy;
}
public Integer getTotalDuration() {
return totalDuration;
}
public void setTotalDuration(Integer totalDuration) {
this.totalDuration = totalDuration;
}
public List<Song> getSongs() {
return songs;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
}
Song.java
#Entity
#Table(name = "songs", schema = "dbo")
public class Song {
#Id
#GeneratedValue
#Column(name = "song_id")
private Integer songId;
#Column(name = "song_name")
private String songName;
#Column(name = "album_id")
private Integer songAlbumId;
#Column(name = "song_duration")
private String songDuration;
#ManyToOne(targetEntity = Album.class)
private Album album;
public Integer getSongId() {
return songId;
}
public void setSongId(Integer songId) {
this.songId = songId;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
public Integer getSongAlbumId() {
return songAlbumId;
}
public void setSongAlbumId(Integer songAlbumId) {
this.songAlbumId = songAlbumId;
}
public String getSongDuration() {
return songDuration;
}
public void setSongDuration(String songDuration) {
this.songDuration = songDuration;
}
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
this.album = album;
}
}
My Controller:
SongsController.java
#RestController
#RequestMapping("/songs")
public class SongsController {
#Autowired
private SongRepository songs;
#Autowired
private AlbumRepository albums;
#Autowired
private Services services;
#GetMapping("/")
public List<SongViewModel> getAllSongs() {
List<SongViewModel> listOfAllSongs = new ArrayList<>();
songs.findAll().forEach(song -> listOfAllSongs.add(services.translateToViewModel(song)));
return listOfAllSongs;
}
}
Services class:
Services.java:
#Service
public class Services {
#Autowired
private SongRepository songs;
#Autowired
private AlbumRepository albums;
public SongViewModel translateToViewModel(Song song) {
SongViewModel model = new SongViewModel();
model.setSongId(song.getSongId());
model.setSongAlbumId(song.getSongAlbumId());
model.setSongName(song.getSongName());
model.setSongDuration(song.getSongDuration());
model.setSongAlbumName(albums.findById(song.getSongAlbumId()).get().getAlbumName());
return model;
}
public AlbumViewModel translateToViewModel(Album album) {
AlbumViewModel model = new AlbumViewModel();
return model;
}
}
My View Models:
SongViewModel:
public class SongViewModel {
private String songName;
private String songAlbumName;
private String songDuration;
private Integer songId;
private Integer songAlbumId;
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
public String getSongAlbumName() {
return songAlbumName;
}
public void setSongAlbumName(String songAlbumName) {
this.songAlbumName = songAlbumName;
}
public String getSongDuration() {
return songDuration;
}
public void setSongDuration(String songDuration) {
this.songDuration = songDuration;
}
public Integer getSongId() {
return songId;
}
public void setSongId(Integer songId) {
this.songId = songId;
}
public Integer getSongAlbumId() {
return songAlbumId;
}
public void setSongAlbumId(Integer songAlbumId) {
this.songAlbumId = songAlbumId;
}
}
Logged SQL query:
select song0_.song_id as song_id1_1_, song0_.album_album_id as album_al5_1_, song0_.album_id as album_id2_1_, song0_.song_duration as song_dur3_1_, song0_.song_name as song_nam4_1_ from dbo.songs song0_
Error:
ERROR: column song0_.album_album_id does not exist
My Database Schema (PostgreSQL 12.10.1)
This is my first time using Spring Boot and JPA. What have I done wrong here?
From the error message, I am guessing that it is trying to find a column called album_album_id which does not exist in my database and as a result is unable to find it; but why is it searching for that particular column? (My guess is I've messed up the relationship attributes).
Your mapping is wrong. Song should look like this:
#Entity
#Table(name = "songs", schema = "dbo")
public class Song {
#Id
#GeneratedValue
#Column(name = "song_id")
private Integer id;
#Column(name = "song_name")
private String name;
#Column(name = "album_id")
private Integer albumId;
#Column(name = "song_duration")
private String duration;
#ManyToOne
#JoinColumn(name = "album_id", insertable = false, updatable = false)
private Album album;
}
and Album like this:
#Entity
#Table(name = "albums", schema = "dbo")
public class Album {
#Id
#GeneratedValue
#Column(name = "album_id")
private Integer id;
#Column(name = "album_name")
private String name;
#Column(name = "released_by")
private String releasedBy;
#Column(name = "total_duration")
private Integer totalDuration;
#OneToMany(mappedBy = "album")
private List<Song> songs;
}
By the way,
it's a little strange to have song duration formatted as String and album duration as Integer.
if you're willing to go from CrudRepository to JpaRepository, you may want to use Spring data projection instead of manually recasting your song to SongViewModels
Here's a little example of interface projection for your question
Your Song entity class should be changed like follows.
#Entity
#Table(name = "songs", schema = "dbo")
public class Song {
#Id
#GeneratedValue
#Column(name = "song_id")
private Integer songId;
#Column(name = "song_name")
private String songName;
#Column(name = "song_duration")
private String songDuration;
#JoinColumn(name = "album_id", referencedColumnName = "album_id")
#ManyToOne
private Album album;
public Integer getSongId() {
return songId;
}
public void setSongId(Integer songId) {
this.songId = songId;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
public Integer getSongAlbumId() {
return songAlbumId;
}
public void setSongAlbumId(Integer songAlbumId) {
this.songAlbumId = songAlbumId;
}
public String getSongDuration() {
return songDuration;
}
public void setSongDuration(String songDuration) {
this.songDuration = songDuration;
}
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
this.album = album;
}
}
now you can get alubm_id by song enntity using song.getAlbum().getAlbumId()

Foreign key always Null in DB

I got this error in Spring: enter image description here When I try to join two table entities.
And the foreign key is always Null in DB, Why?
My Entity Classes - Task, ListeExecJob.
Please, help me
Task :
#SuppressWarnings("serial")
#Entity
#Table(name ="task")
public class Task implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;
#Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;
#Column(name = "description", length = 100, nullable = false)
private String description;
#Column(name = "script", length = 100, nullable = false)
private String script;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "date_execution")
private Date date_execution;
#Column(name = "active")
private boolean active;
#ManyToOne
#JoinColumn(name="id_liste")
private ListeExecJob liste;
public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom_job() {
return nom_job;
}
public void setNom_job(String nom_job) {
this.nom_job = nom_job;
}
public String getType_commande() {
return type_commande;
}
public void setType_commande(String type_commande) {
this.type_commande = type_commande;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public boolean getActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Task() {
}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
Date date_execution, boolean active) {
super();
this.id=id;
this.nom_job = nom_job;
this.type_commande = type_commande;
this.description = description;
this.script = script;
this.date_execution = date_execution;
this.active=active ;
}
}
ListeExecJob.java
____________________________________________________
#SuppressWarnings("serial")
#Entity
#Table(name ="liste")
#JsonIgnoreProperties(
value = {"dateCreation"},
allowGetters = true
)
public class ListeExecJob implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idListe")
private int idListe;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "date_creation")
#CreatedDate
private Date date_creation;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#JoinColumn(name = "date_execution")
private Date date_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "fin_execution")
private Date fin_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "next_execution")
private Date next_execution;
#OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JsonIgnore
private List<Task> task;
public int getIdListe() {
return idListe;
}
public void setIdListe(int idListe) {
this.idListe = idListe;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getFin_execution() {
return fin_execution;
}
public void setFin_execution(Date fin_execution) {
this.fin_execution = fin_execution;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonIgnore
public List<Task> getTask() {
if (task == null) {
task = new ArrayList<>();
}
return this.task;
}
public void addTask(Task task) {
getTask().add((Task) task);
((Task) task).setListe(this);
}
public void removeTask(Task task) {
getTask().remove(task);
task.setListe(null);
}
#JsonSetter
public void setTask(List<Task> task) {
this.task = task;
}
public ListeExecJob() {
}
public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b
fin_execution,
Date next_execution) {
super();
this.idListe = idListe;
this.status = status;
this.date_creation = date_creation;
this.date_execution = date_execution;
this.fin_execution = fin_execution;
this.next_execution = next_execution;
}
}
Task service
#Service
#Transactional(propagation= Propagation.SUPPORTS)
#Primary
public class TaskService {
#Autowired
private TaskRepository repository;
#Autowired
private ListeExecJobService service;
#Autowired
public TaskService(TaskRepository repository) {
super();
this.repository = repository;
}
public List<Task> listAllTask(){
return repository.findAll();
}
public Task addTask(Task task){
ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());
ab.addTask(task);
return repository.save(task);
/* task.setListe(ab);
System.out.println(task.getListe().getIdListe());
ab.addTask(task);*/
}
public Task updateTask(Integer id , Task task){
Task job1 = new Task();
job1 = task;
job1.setId(id);
return addTask(job1);
}
public void deleteTask(Integer id){
repository.deleteById(id);
}
public Task getByreferenece(Integer id){
return repository.findById(id).isPresent()? repository.findById(id).get():null;
}
}
ListeExecJobService
#Service
#Transactional
#Primary
public class ListeExecJobService {
#Autowired
private ListeExecJobRepository SJIRepos;
#Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
super();
this.SJIRepos = SJIRepos;
}
public List<ListeExecJob> listAllListeExecJob(){
return SJIRepos.findAll();
}
public ListeExecJob addListeExecJob(ListeExecJob SJI){
return SJIRepos.save(SJI);
}
public ListeExecJob getByreferenece(Integer idListe){
return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;
}
public void deleteListeExecJob(Integer idListe){
SJIRepos.deleteById(idListe);
}
public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
ListeExecJob sji01 = new ListeExecJob();
sji01 = sji;
sji01.setIdListe(idListe);
return addListeExecJob(sji01);
}
public void deleteById(Integer idListe) {
SJIRepos.deleteById(idListe);
}
}
try #JoinColumn(name="id_liste",referencedColumnName = "idListe") in the task class, you have a problem in the join column

dataaccess error--> getInt not implemented for class oracle.jdbc.driver.T4CDateAccessor

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.

Categories