How to select childs from a superclass? - java

I have a basic JPA mapping with a superclass containing a list.
How can I select all List row entries from the database for a specific person?
class Person {
#Id
int id;
#OneToMany
List<Payment> payments;
}
//SELECT <all payments> from Person p WHERE p.id = 1

You can simply do SELECT person.payments FROM Person person JOIN person.payments WHERE person.id = ?.
You would cast the return list() to a List<Payment>

Related

How to conditionally WHERE populated foreign keys with OneToMany Entity?

I am assuming a setup as described in: https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/
Employee:
#JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;
Account:
#ManyToOne
private EmployeeEntity employee;
Using JPA/Hibernate, how can I fetch results using a WHERE condition that applies to Account. In other words, query something like Select all employees with accounts with sales > 0 or similar.
I'm assuming sales column as INT in account table.
you can write a query like following:
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e JOIN Account a ON e.id = a.accounts.employee_id WHERE a.sales > :sales", Employee.class);
query.setParameter("sales", salesInput);
List<Employee> items = query.getResultList();
I would recommend you to go through this tutorial to learn about CRUD operations in Hibernate Associations
https://www.dineshonjava.com/spring-crud-example-using-many-to-one/

How can I left join two unrelated tables using JPA Criteria?

Here I have two tables users and orders, users has two fields first_name and last_name, and orders has a field full_name. For some reason, I cannot change the database schema.
Now I have a query:
SELECT u.* FROM users u LEFT JOIN orders o ON o.full_name = CONCAT(u.first_name, ' ', u.last_name)
And I need convert this into JPA Specifications because it is a part of other specifications. The following is my try:
Entity:
#Entity
#Table(name = "users")
class User {
#Id
private Integer id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
}
#Entity
#Table(name = "orders")
class Order {
#Id
private Integer orderId;
#Column(name = "full_name")
private String fullName;
}
The problem is, what should I fill in the following statement for the first parameter
(root, query, criteraBuilder) -> {
Join<User,Order> join = root.join(???,JoinType.LEFT);
join.on(blablabla_condition)
}
Is this doable?
Thanks
In order to go down the route you are trying to implement, you'll have to map the association within the User/Order as a #OneToOne or #OneToMany lazy association based on whether there can be multiple orders for a user or not. For that you'll have to map the join operation that is the complicated logic you have mapped in the native query at the top. I suggest you take a look in the #JoinFormula and #JoinColumnOrFormula as ways to map that join.
First attempt...
What if you make a method with your native query?
#Query(value = "SELECT u.* FROM users u LEFT JOIN orders o ON o.full_name = CONCAT(u.first_name, ' ', u.last_name)", nativeQuery = true)
List<User> getUserJoinedWithOrder();
UPDATED
Specification<One> p = (user, query, cb) -> {
return cb.equal(
query.from(Order.class).get("fullName"),
cb.concat(user.get("firstName"), cb.concat(" ", user.get("lastName"))));
};
List<One> list = oneRepo.findAll(p);

How can I use Hibernate to load a list of entities and a subset of those entities' related entities?

I have a query I'd like to run against a table, let's call it parent where I'm grabbing all rows that match a certain criteria. In SQL:
select * from parent where status = 'COMPLETE';
I have this table and another related table (child) defined as Hibernate entities such that:
#Entity
#Table(name = "parent")
public class Parent {
//...
#OneToMany(mappedBy = "parent")
private Set<Child> children;
//...
}
#Entity
#Table(name = "child")
public class Child {
//...
#ManyToOne
#JoinColumn(name = "parent_id")
private Parent parent;
#Column(name = "key")
private String key;
//...
}
I'd like my query to ALSO pull two optional child records where key is one of two values. So, in SQL:
select *
from parent p, child ca, child cb
where p.status = 'COMPLETED'
and p.id *= ca.parent_id
and ca.key = 'FIRST_KEY'
and p.id *= cb.parent_id
and cb.key = 'SECOND_KEY';
I could do this in Hibernate by just grabbing the result from the first query and iterating over the children collection looking for the rows I want but that's terribly inefficient: one query that does two outer joins vs one query + an additional query for each looking for the children I care about.
Is there a way to replicate the outer joins in the query above in Hibernate where the objects returned will have the children collection only populated with the two (or less, since they are optional) entities I am interested in?
You don't need two outer joins. You could simply use this HQL and Hibernate will add the right children to the right parent:
List<Parent> parentList = session
.createQuery("from Parent p left join fetch p.children c" +
" where p.status = 'COMPLETE' " +
" and (c.key = 'FIRST_KEY' or c.key = 'SECOND_KEY')")
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
for(Parent parent:parentList) {
System.out.println(parent);;
}
Hope that solves your problem.

Hibernate DetachedQuery and Spring's HibernateTemplate with Restriction giving wrong results

My data structure is like this
Department
-> Employees
-> Gender
-> CityID -> Cities
->CityID
->CountryID -> Countries
-> CountryID
Department Class:
public class Department {
#OneToMany(mappedBy = "departmentid", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Employee> employees = new HashSet<>();
}
I build Crteria like this:
DetachedCriteria criteria = DetachedCriteria.forClass(Department.class);
DetachedCriteria detlCrit = criteria.createCriteria("employees");
detlCrit.add(Restrictions.eq("gender", "MALE"));
detlCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
I have 1 Department, 2 Employees in the Tables (1 male, 1 female).
When I excecute this criteria iam expecting Hibernate build one 'Department' object, one 'Employee' object, and city, country etc.,
But what iam getting is 1 Department, 2 Employees.
When I see the queries executed by Hibernate in logs, it shows two queries
First Query:
Select * from Department, Employee
Left outer join City on Employee.cityID = City.cityID
Left outer join Country on City.countryID = City.countryID
Where Employee.DeptID = Department.DeptID
AND Employee.Gender = 'MALE';
Second query:
Select * from Employee
Left outer join City on Employee.cityID = City.cityID
Left outer join Country on City.countryID = City.countryID
Where Employee.DeptID = Department.DeptID;
Second query is wrong there is no Restriction applied on Gender='MALE';
What iam doing wrong? any suggestions? how to solve this?
sorry queries may be not exactly correct, but you got the idea.
Any more details needed please ask, I can provide.
Thanks in advance..
Try this,using SessionFactory.
#Autowired
private SessionFactory sessionFactory;
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Department.class);
criteria.add(Restrictions.eq("gender", "MALE"));
Hope I was useful.
The first query is selecting Department entities and the filtering is applied as you specified in your where clause.
But you cannot truncate associations, you always have to fetch them all eagerly or lazily. That's because Hibernate has to maintain consistency guarantees when flushing back the loaded Department entity and possibly cascading the employees state back to the database.
The second query is most likely because you use a FetchType.EAGER on your employees collection:
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "department", orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
Once the Department is fetched, the employee collection is fetched eagerly as well.
Try with an HQL query liken this one:
select distinct d
from Department d
left join fetch d.employees e
where e.gender = :gender

JPQL for Entities with No Items in ManyToMany Relationship

Simple JPA/JPQL question. I have an entity with a ManyToMany relationship:
#Entity
public class Employee {
#ManyToMany
#JoinTablename="employee_project"
joinColumns={#JoinColumn(name="employee_id"}
inverseJoinColumns={#JoinColumn(name="project_id"})
private List<Project> projects;
What is the JPQL query to return all the Employees that do not have any projects?
from Employee e where not exists elements(e.projects)
or
from Employee e where size(e.projects) = 0
JQPL does have dedicated IS [NOT] EMPTY comparison operator for checking is collection empty:
SELECT e FROM Employee e WHERE e.projects IS EMPTY

Categories

Resources