How to get data from tables in spring data jpa? - spring-boot

I have two tables
#Entity
#Table(name = "TAX_CATEGORY")
public class TaxCategory {
#Id
#GeneratedValue
#Column(name = "ID", nullable = false)
private long id;
#Column(name = "CATEGORY", nullable = false)
private String category;
#Column(name = "TAX", nullable = false)
private Double tax;
#Entity
#Table(name = "PRODUCT")
public class Product {
#Id
#GeneratedValue
#Column(name = "ID", nullable = false)
private long id;
#Column(name = "PRICE", nullable = false)
private Double price;
#Column(name = "NAME", nullable = false)
private String name;
#OneToOne
#JoinColumn(name = "TAX_CATEGORY_ID")
private TaxCategory taxCategory;
Now I want to query
"Select p.name, p.price, t.tax from Product p, TaxCategory t join p.taxCategory.id=t.id"
So List it would return is
ProductName ProductPrice Tax
but I am not able to get this data from two tables. Single table data is working fine.
public interface CustomRepositoryCustom {
public void customMethod();
}
public interface CustomRepository
extends JpaRepository<Account, Long>, CustomRepositoryCustom { }
public class CustomRepositoryImpl implements CustomRepositoryCustom {
public void customMethod() {
Query nativeQuery = entityManager.createNativeQuery("Select p.name, p.price, t.tax from Product p, TaxCategory t join p.taxCategory.id=t.id");
return query.getResultList();
}
}
This throws exception that object is not managed bean. If I create custom object then also it gives similar type of issues.

Use the following JPA query to get the both tables data. Here used jpa query to fetch the product. From product object, can get the taxCategory.
public interface CustomRepository extends JpaRepository<Account, Long>, CustomRepositoryCustom {
Query("select product from Product as product join fetch product.taxCategory as taxCategory where taxCategory.id = :taxCategoryId")
public Product getProductByCategory(#Param Long taxCategoryId);
}

Instead of query method you can directly define JPA method to find products based on category Id as.
#Repository
#RepositoryRestResource
public interface ICountryRepository extends JpaRepository<Product , Long > {
List<Product> findByTaxCategory_Id(#Param Long Id);
}

Related

JPA ManyToMany fails with "must have same number of columns as the referenced primary key"

I have three tables customer, product and sales. sales is the join table to store the customer's products as shown below:
customer, product and Sales tables
My Entities defined as described below:
Customer.java
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="c_id")
private String customerId;
#Column(name="customer_name")
private String customerName;
#ManyToMany
#JoinTable(
name = "sale",
joinColumns = #JoinColumn(name = "c_id"),
inverseJoinColumns = #JoinColumn(name = "p_id"))
private Set<Product> customerProducts = new HashSet<>();
}
Product.java
#Entity
#Table(name="product")
public class Product {
#Id
#Column(name="p_id")
private String productId;
#Column(name="product_name")
private String productName;
#Column(name="price")
private Double price;
// ... Setters & Getters
}
Sales.java
#Entity
#Table(name="sales")
public class Sales {
#EmbeddedId
private SalesPK salesId;
#Column(name="qty")
private Long qty;
// ... Setters & Getters
}
SalesPK.java
#Embeddable
public class SalesPK implements Serializable {
#Column(name = "c_id")
private String customerId;
#Column(name = "p_id")
private String productId;
public SalesPK() {}
public SalesPK(String customerId, String productId) {
this.customerId = customerId;
this.productId = productId;
}
}
CustomerRepository.java
#Repository
public interface CustomerRepository extends CrudRepository<Customer, String> {
#Query("select customer from Customer customer " +
"left join fetch customer.customerProducts " +
"where customer.customerName = :customerName")
public Customer getCustomerPurchasedProducts(String customerName);
}
My Spring boot application fail to start with following exception:
org.hibernate.MappingException: Foreign key (FK7wwx8x75009xqb1y0tawm8rty:SALES [p_id])) must have same number of
columns as the referenced primary key (SALES [c_id,p_id])
What am I missing here? I have followed the notes as described here in https://www.baeldung.com/jpa-many-to-many
UPDATE:
There is no issue with above solution, I have misspelled "sales" table in #ManyToMany declaration changing from "sale" to "sales" fixed the issue. Strange behavior why it didn't compline about missing table instead it complain about actual composite primary key definition.
Following code Fixed the issue:
#ManyToMany
#JoinTable(
name = "sales",
joinColumns = #JoinColumn(name = "c_id"),
inverseJoinColumns = #JoinColumn(name = "p_id"))
private Set<Product> customerProducts = new HashSet<>();
}
I would map these classes a bit differently:
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="c_id")
private String customerId;
#Column(name="customer_name")
private String customerName;
#OneToMany(mappedBy = "customer")
private Set<Sale> customerSales = new HashSet<>();
}
#Entity
#Table(name="product")
public class Product {
#Id
#Column(name="p_id")
private String productId;
#Column(name="product_name")
private String productName;
#Column(name="price")
private Double price;
}
#Entity
#Table(name="sales")
public class Sales {
#EmbeddedId
private SalesPK salesId;
#MapsId("customerId") // maps customerId attribute of embedded id
#ManyToOne
Customer customer;
#MapsId("productId") // maps productId attribute of embedded id
#ManyToOne
Product product;
#Column(name="qty")
private Long qty;
// ... Setters & Getters
}
#Embeddable
public class SalesPK implements Serializable {
#Column(name = "c_id")
private String customerId;
#Column(name = "p_id")
private String productId;
public SalesPK() {}
public SalesPK(String customerId, String productId) {
this.customerId = customerId;
this.productId = productId;
}
}

JPA Failing to produce a proper SQL query when a parameter has a composite primary key

Today I came across a weird bug while trying to test a JPA update query and I'm wondering if this a SpringBoot bug.
I have the following entities
An Entry entity
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor(access = AccessLevel.PROTECTED, force = true)
public class Entry {
#Id
private String id;
#ManyToOne(targetEntity = User.class)
#JoinColumn(referencedColumnName = "username")
#NotNull
private final User username;
#Enumerated(EnumType.STRING)
#NotNull
private Type type;
#ManyToOne(targetEntity = Category.class)
#JoinColumns({#JoinColumn(referencedColumnName = "name"),#JoinColumn(referencedColumnName = "type"),#JoinColumn(referencedColumnName = "username")})
#NotNull
private Category category;
#Size(max = 45)
#NotBlank
private String description;
#NotNull
private Double amount;
#NotNull
private final Date createdAt;
private Timestamp lastUpdate;
#NotNull
private Boolean isDeleted;
public enum Type{
Income,Expense
}
}
A Category entity with a composite key
#Entity
#NoArgsConstructor(access = AccessLevel.PROTECTED, force = true)
#Setter
#Getter
#EqualsAndHashCode(of = {"id"})
#ToString(of = {"id"})
public class Category {
#EmbeddedId
private CategoryId id;
private final Timestamp createdAt = Timestamp.from(Instant.now());
#ManyToOne(targetEntity = User.class)
#JoinColumn(referencedColumnName = "username")
private final User user;
#OneToMany(cascade = CascadeType.ALL,mappedBy = "category")
private List<Entry> entries;
public Category(String name, Type type, User user){
this.id = new CategoryId(name,type,user.getUsername());
this.user = user;
}
}
A CategoryID that is the embeddable composite key of the Category entity
#Data
#Embeddable
#AllArgsConstructor
#NoArgsConstructor(access = AccessLevel.PROTECTED)
#EqualsAndHashCode(of = {"name","type","username"})
public class CategoryId implements Serializable {
private String name;
#Enumerated(EnumType.STRING)
private Type type;
private String username;
}
The following repository
#Repository
public interface EntryRepository extends JpaRepository<Entry, String> {
Optional<Entry> findEntryById(String id);
#Modifying(clearAutomatically = true, flushAutomatically = true)
#Query(value = "UPDATE Entry e SET e.username = :username, e.type = :type, e.category = :category, e.description = :description, e.amount = :amount, e.createdAt = :date, e.lastUpdate = :lastUpdate, e.isDeleted = :isDeleted WHERE e.id = :id")
void update(#Param("id") String id,
#Param("username") User username,
#Param("type") Entry.Type type,
#Param("category") Category category,
#Param("description") String description,
#Param("amount") Double amount,
#Param("date") Date date,
#Param("lastUpdate") Timestamp lastUpdate,
#Param("isDeleted") Boolean isDeleted);
}
And finally the following Unit Test
#Test
void update() {
//given
User testUser = userRepository.save(new User("testUser#test.com","000000000000000000000000000000000000000000000000000000000000"));
Category testCategory = categoryRepository.save(new Category("Test Category", Entry.Type.Income,testUser));
Entry testEntry = new Entry("testEntry",testUser, Entry.Type.Income,
testCategory, "test",
0.0, new Date(343), from(now()), false);
System.out.println(testCategory);
entryRepositoryUnderTest.save(testEntry);
//when
entryRepositoryUnderTest.update("testEntry",testUser,Expense,testCategory,"testUpdated",1.0,new Date(346), from(now()),true);
Optional<Entry> actual = entryRepositoryUnderTest.findEntryById("testEntry");
System.out.println(actual.get().getCategory());
//then
assertThat(actual.get().getUsername()).isEqualTo(testUser);
assertThat(actual.get().getType()).isEqualTo(Expense);
assertThat(actual.get().getCategory()).isEqualTo(testCategory);
assertThat(actual.get().getDescription()).isEqualTo("testUpdated");
assertThat(actual.get().getAmount()).isEqualTo(1.0);
assertThat(actual.get().getIsDeleted()).isEqualTo(true);
}
When I run the test it fails and I get the following error message:
could not execute update query; SQL [update entry set username_username=?, type=?,category_name=?=category_type=?, description=?, amount=?, created_at=?, last_update=?, is_deleted=? where id=?]; nested exception is org.hibernate.exception.DataException: could not execute update query
As you can see here when SpringBoot is trying to produce a SQL query statement from my #Query parameter it can not properly extract the Category field from the parameters and inject it's composite embeddable key into the SQL statement. It has no problem extracting the User parameter because the User is an entity with an id that is not composite.
Is this a SpringBoot bug or am I missing something?
EDIT:
This is the structure of the database

fetch list based on id present in another entity

this is my order entity,
#Data
#NoArgsConstructor
#AllArgsConstructor
#ToString
#Entity
#Table(name = "ordertab")
public class Order {
#Id
private int orderId;
private String orderDate;
#ManyToMany(targetEntity = Medicine.class,cascade = CascadeType.ALL)
#JoinTable(name="ord_med",
joinColumns = {#JoinColumn(name="ord_id")},
inverseJoinColumns = {#JoinColumn(name="med_id")})
private List<Medicine> medicineList;
private String dispatchDate;
private float totalCost;
#ManyToOne(targetEntity = Customer.class,cascade = CascadeType.ALL)
#JoinColumn(name= "custord_fk",referencedColumnName = "customerId")
private Customer customer;
private String status;
}
and this is my medicine entity,
#Data
#NoArgsConstructor
#AllArgsConstructor
#ToString
#Entity
public class Medicine {
#Id
private String medicineId;
private String medicineName;
private float medicineCost;
private LocalDate mfd;
private LocalDate expiryDate;
**#ManyToMany(cascade = CascadeType.ALL, mappedBy = "medicineList")
private List<Order> orderList;** //order/ medicine many to many mapping
// OneToOne Mapping
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "categoryId", referencedColumnName = "categoryId")
private Category category;
in my order service interface i have a method,
List showAllOrder(string medId);
I have to fetch all orders that has the matching med id.
this many to many mapping have created a additional table ord_med with two columns named ord_id,med_id(type foreign keys).In addition to that due to this bidirectional mapping(i believe it is) while creating object of medicine entity its asking me to add orderlist ,how to approach this method or how exactly should i solve this. thankyou.
in your OrderRepository you can implements this method
findByMedicineId(String id);
if i go for findByMedicineId(String id);
it gives error saying no property medicineId is found in Order entity,cuz the property medicineId is in Medicine entity,while defining custom method in repository follows rules, refer https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
anyway I have found the solution for this,
public List<Order> getOrderListBasedOnMedicineId(String medicineid) {
Optional<Medicine> med=medicineRepo.findById(medicineid);//find if medicine is present in database with the id.
if(med.isEmpty()) {
return null;
}
List<Order> orders = medicineServ.getOrderList(); //getorderlist defined in service implementation of medicine.
List<Order> ordersWithMedId = new ArrayList();//new list to add all orders that has atleast one medicineId that matches.
for(int i=0;i<orders.size();i++) {
List<Medicine> medicines= orders.get(i).getMedicineList();
for(int j=0;j<medicines.size();j++) {
ordersWithMedId.add(orders.get(i));
}
}
return ordersWithMedId;//returning the list of orders.
}
#Override
public List<Order> getOrderList() {//medicine service implementation
return orderRepo.findAll();
}
//OrderController
#GetMapping("/orders/list/{id}")
public ResponseEntity<List<Order>> getOrderListBasedOnMedicineId(#PathVariable("id") String id) {
List<Order> ord= orderService.getOrderListBasedOnMedicineId(id);
if(ord==null) {
throw new OrderNotFoundException("Order not found with medicine id:"+id);
}
return new ResponseEntity<List<Order>>(orderService.getOrderListBasedOnMedicineId(id),HttpStatus.OK);
}

Spring Data JPA ManyToOne query null

I've started to learn Spring Boot, I've created two entities Invoice and YearDate
When I try to search by year(id), in my log query I got null (see this part of log query)
http://localhost:8080/appapi/invoices/search/findByYearId?year=1
from invoice invoice0_ left outer join year_date yeardate1_ on invoice0_.year_id=yeardate1_.id where yeardate1_.id is null limit?
I'm using Lombok also for getters and setters
Here are all my class entities, SQL tables, and JpaRepository interface :
SQL foreign key :
KEY `fk_year` (`year_id`),
CONSTRAINT `fk_year` FOREIGN KEY (`year_id`) REFERENCES `YearDate` (`id`)
YearDate class :
#Entity
#Table(name="YearDate")
#Data
public class YearDate {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "year_value")
private String yearValue;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "year")
private Set<Invoice> invoices;
}
Invoice class:
#Entity
#Table(name="invoice")
#Data
public class Invoice {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "year_id", nullable = false)
private YearDate year;
#Column(name = "description")
private String description;
}
**And The Invoice Interface:**
#CrossOrigin("http://localhost:4200")
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Page<Invoice> findByYearId(#RequestParam("year") Long id, Pageable page);
}
Work for me.
try to extract call in rest controller and log params
#GetMapping(value = "/invoices")
public Page<Invoice> getInvoices(#RequestParam("yearId") Long yearId) {
Page<Invoice> byYearId = invoiceRepository.findByYearId(yearId, PageRequest.of(0, 10));
return byYearId;
}
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Page<Invoice> findByYearId(Long id, Pageable page);
}
#ManyToOne
#JoinColumn(name = "year_id", nullable = false)
#JsonIgnoreProperties("invoices")
private YearDate year;
#OneToMany(mappedBy = "year")
#JsonIgnoreProperties("year")
private Set<Invoice> invoices;
Generated SQL :
Hibernate:
select
invoice0_.id as id1_0_,
invoice0_.description as descript2_0_,
invoice0_.name as name3_0_,
invoice0_.year_id as year_id4_0_
from
invoice invoice0_
left outer join
year_date yeardate1_
on invoice0_.year_id=yeardate1_.id
where
yeardate1_.id=? limit ?
Hibernate:
select
yeardate0_.id as id1_5_0_,
yeardate0_.year_value as year_val2_5_0_
from
year_date yeardate0_
where
yeardate0_.id=?
-> ADD #JsonIgnoreProperties("invoices") and #JsonIgnoreProperties("year") to entities to avoid infinite json recusrsion.
I've disabled Lombok and it works
try pass him a Year object not id is better
#CrossOrigin("http://localhost:4200")
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Page<Invoice> findByYear(YearDate year, Pageable page);
}
and in your service get this year
for exemple I create a getYears method in service:
#Service
public class YearService{
#Autowired
private YearRepository yearRepository;
#Autowired
private InvoiceRepository invoiceRepository;
getYears(idYear:Long){
YearDate yearParam=yearRepository.findById(id).get();
Page<Invoice> invoices=invoiceRepository.findByYear(yearParam,YourPagination)
}
}

Select on Northwind database using JPA and JDBC Template

I would like to perform select statement on Northwind database like this bellow.
select distinct b.*, a.CategoryName
from Categories a
inner join Products b on a.CategoryID = b.CategoryID
where b.Discontinued = 'N'
order by b.ProductName;
I have two problems regarding this operation :
I have created POJO for tables categories and products like bellow
Table Products
#Entity
public class Products {
#Id
private Long productid;
private String productname;
private Long supplierid;
#ManyToOne
#JoinColumn(name = "categories", referencedColumnName = "categoryid")
private Categories categoryid;
private String quantityperunit;
private Double unitprice;
private Long unitsinstock;
private Long unitsonorder;
private Long reorderlevel;
private String discontinued;
Table Categories
#Entity
public class Categories {
#Id
private Long categoryid;
private String categoryname;
private String description;
private String picture;
Now I have no idea how to write rowmapper for this tables (please find below ????)
private static final RowMapper<Products> productsRowMapper = (rs, rowNum) ->{
Products products = new Products();
products.setProductid(rs.getLong("ProductID"));
products.setProductname(rs.getString("ProductName"));
products.setSupplierid(rs.getLong("SupplierID"));
products.setCategoryid(rs.?????
products.setQuantityperunit(rs.getString("QuantityPerUnit"));
products.setUnitprice(rs.getDouble("UnitPrice"));
products.setUnitsinstock(rs.getLong("UnitsInStock"));
products.setUnitsonorder(rs.getLong("UnitsOnOrder"));
products.setReorderlevel(rs.getLong("ReorderLevel"));
products.setDiscontinued(rs.getString("Discontinued"));
return products;
};
the second problem is that I don't know if the annotations on the column categoryid in the table products are correct?
After correction
#Repository
public class JdbcProductsDao implements ProductsDao{
private final JdbcTemplate jdbcTemplate;
#Autowired
public JdbcProductsDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private static final RowMapper<Products> productsRowMapper = (rs, rowNum) ->{
Products products = new Products();
products.setProductid(rs.getLong("ProductID"));
products.setProductname(rs.getString("ProductName"));
products.setSupplierid(rs.getLong("SupplierID"));
products.setCategoryid(new Categories(rs.getString("CategoryName")));
products.setQuantityperunit(rs.getString("QuantityPerUnit"));
products.setUnitprice(rs.getDouble("UnitPrice"));
products.setUnitsinstock(rs.getLong("UnitsInStock"));
products.setUnitsonorder(rs.getLong("UnitsOnOrder"));
products.setReorderlevel(rs.getLong("ReorderLevel"));
products.setDiscontinued(rs.getString("Discontinued"));
return products;
};
public Products findByProductName(String productname) {
String sql = "SELECT * FROM products WHERE ProductName = ?";
return jdbcTemplate.queryForObject(sql, productsRowMapper, productname);
}
public List<Products> sortByProductName(){
String sql = "SELECT * FROM products order by ProductName asc";
return jdbcTemplate.query(sql, productsRowMapper);
}
Table Categories
#Entity
public class Categories {
#Id
private Long categoryid;
#Column(name = "CategoryName")
private String categoryname;
private String description;
private String picture;
#OneToMany(mappedBy="categoryid")
private List<Products> products;
Table Products
#Entity
public class Products {
#Id
private Long productid;
#Column(name = "ProductName")
private String productname;
private Long supplierid;
#ManyToOne
private Categories categoryid;
private String quantityperunit;
private Double unitprice;
private Long unitsinstock;
private Long unitsonorder;
private Long reorderlevel;
private String discontinued;
Now I have no idea how to write rowmapper for this tables (please find
below ????)
You have to set an Object like this :
products.setCategoryid(new Categories(rs.getString("a.categoryname"));
I assume you have an constructor Categories(String categoryname)
Note : If you want to get more information, you have to change your query and your constructor as well.
the second problem is that I don't know if the annotations on the
column categoryid in the table products are correct?
I think there are no need to use #JoinColumn(name = "categories", referencedColumnName = "categoryid") just use :
#ManyToOne
private Categories categoryid;
In your Categories entities add this :
#OneToMany(mappedBy="categoryid")
List<Products> products;

Resources