Entity Graph for nested associations of tables in Spring JPA - spring

There are 3 tables in my db:
SalesOrderMaster
SalesOrderDetail
CustomerMaster
I have repository class SalesOrderDetailRespository.java which has this method findAll()
#EntityGraph(attributePaths = {"SalesOrderMaster"}, type = EntityGraph.EntityGraphType.FETCH)
List<SalesOrderInfo> findAll(#Nullable Specification<SalesOrderInfo> spec);
This is till now fetching the SalesOrderMaster record and associated SalesOrderDetails records. Now my requirement is in SalesOrderInfo class , I have added a new property for showing the Customer Information like Name , country which are there in CustomerMaster table.
The customerMaster table is related to SalesOrderMaster by customerId column. How do I add CustomerMaster table in the existing EntityGraph so that I can get this info?

Related

How to get column name from JPA

My code:
empDet emp = repository.findByActiveFlag("Y");
Here empDet is a entity with 3 columns:
empid
empName
ActiveFlag
Table with 10 rows so i will use foreach
emp.forEach(e-> {
---mycode---
---and here i got values--
});
Now my question is how to get Column name from Jpa or foreach loop
If you have object of Entity class (empDet) in JPA then from that object you can get the all properties of that class.
As you know in JPA class represent table in database and properties represent columns of that table.
if you have an object of empDet e.i emp
empDet emp=repository.findByActiveFlag("Y");
Field[] members = emp.getClass().getDeclaredFields();
for(Field member:members){
System.out.println(member.getName());
}

How to connect three tables using only one entity/class in Spring & Hibernate

I have only one entity which is School - a class (example). I have 7 fields in there and those fields are from 3 different tables. The first table for example is called Classroom, second is the Teachers, third is Subject. The teachers and subject table are connected by a pk: subject_id while the classroom table and teachers table are connected by classroom_id.
I tried secondary tables but it looks like it's not correct. How to connect those tables inside a single entity and write a query in the DAO IMPLementation
You should use Entity per Table.
If you need to select into non database related Model class, you can be done easily with spring-data-jpa.
After create the Model class (like School) just use the following sample to query:
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) " +
"from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}
In this example the programmer has an address field (OneToOne), but you can create any kind of query, the important thing here is the constructor call of the model.
If you want to use plain sql or impl class instead of interface to query, you can use Spring's RowMapper too.
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) "
+ "from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}

Spring mvc with hibernate #OneToMany relationship mapping

enter image description hereI have two table one is Credit and second is Debit. I want #OneToMany relationship. in credit table only single row of data and In debit table multiple row of data
Credit table:
cid
openingBalance
date
debittotal
drawertotal
debittotalplusdrawertotal
todaybusiness
all row of only single row data
Debit table:
did
amounnt
description
amount and description multiple data add
I am using Spring mvc with hibernate project structure is just like below
controller
entity
dao
daoImpl
service
serviceImpl
How to create enitiy with #OneToMany Relationship and when I save that data then all data will save at time into two table
You need Cascade persist for this.
#OneToMany(mappedBy="credit", cascade=CascadeType.PERSIST)
List<Debit> debits;
and then in your dao:
Credit credit = new Credit(......);
credit.setDebits(/*the list of debits*/)
entityManager.persist(credit);
or if you're using springdata jpa :
repository.save(credit);

Hibernate = Criteria to query tables

I would like to query hibernate just by passing it an object and I thought this was supported but I guess it isnt as my query returns all the objects in my Product table.
I have a product and a product has a set of categories and I would like to return all products that have that category.
Category is just an id (which I am passing as null as I want to get by name) and a name which is a string which I am setting on the category object, and then passing to the Product object by adding it to a set attached to the product.
I pass an object to the spring rest client and convert this to a hibernate entity and then I thought I could just pass it to hibernate with the properties I want to filter by set:
public List<Product> getProductsByFilterCriteria(Product productToLocate) {
Session session = sessionFactory.getCurrentSession();
List<Product> products = new ArrayList<Product>();
//Just maps the values
ProductEntity criteria = mapProductCriteriaToEntity(productToLocate);
#SuppressWarnings("unchecked")
List<ProductEntity> productsMatchingCriteria = (List<ProductEntity>)session.createCriteria(ProductEntity.class).add(Example.create(criteria).excludeZeroes()).list();
for(ProductEntity productEntity : productsMatchingCriteria) {
products.add(mapProductEntityToProduct(productEntity));
}
return products;
}
I have set up the product entity with a list which contains a single category, and no other properties are set.
How do I just pass the Product and its set of Categories to hibernate and get out all products which have a Category of whatever the category name is?
From the documentation:
17.8. Example queries
The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.
[...]
Version properties, identifiers and associations are ignored.
(emphasis mine)

Spring-Data JPA: How to make a jpa criteria query

Given this two entities:
post post_category
- id - post_id
- title - name
- text
I'd like to make this query using jpa criteria query:
select * from post
where post.id in (
select post_id from post_category
where name = '<category1>' and name = '<category2>' ... and name = '<categoryN>')
Looking at your query sketch I think it will not return any results. I have changed it to mean name in ('<category1>','<category2>', ...) instead. Which may not match your case.
This assumes that you have your mapping set up properly on your classes for JPA to work. For example
class PostCategory {
private String name;
private Post post;
...
#ManyToOne
public Post getPost() {
return post;
}
...
In which case your DAO code would resemble this (given a List nameValues object)
// Set up the subquery
DetachedCriteria dc = DetachedCriteria.forClass(PostCategory.class)
.setProjection(Projections.property("post.id"))
.add(Restrictions.in("name", nameValues));
Criteria crit = session.createCriteria(Post.class)
.add(Subqueries.eqProperty("id", dc));
But if you want a list of Post objects which have ALL of the categories then you will need to make a separate DetachedCriteria instance for each category and add each as an AND'ed Subquery.

Resources