How to write HQL for left outer join with criteria? - hql

I am new to Hibernate, can anybody correct the HQL for below SQL to find out the unique employees that are working to the client currently. if possible please provide me some links for tutorial.
while parsing the SQL I was able to receive some records from the database & also with Native SQL, but when I use below HQL I could not receive any records.
SQL :
select distinct u.employeeid from employee u
inner join address ad on u.employeeid = ad.employeeid
left join company cp on (ad.oldcompanyid = cp.currentcompanyid and cp.wokingornot='Y')
left join client cl on (ad.oldcompanyid = cl.currentcompanyid and cl.wokingornot='Y')
where (u.lastdate is null and ad.lastdate is null)
and (cp.wokingornot = 'Y' or cl.wokingornot = 'Y');
please correct the HQL listed below :
select distinct u from employee u ,address uo,company tp ,client mp
inner join u.address uo
left join uo.company tp with tp.wokingornot= true
left join uo.client mp with mp.wokingornot= true
where (u.lastdate is null and uo.lastdate is null)
and (tp.wokingornot= true or mp.wokingornot= true );
Below are the entities which I am looking for the HQL:
public class employee {
public Int employeeid ;
public set<address> address;
public Date lastdate;
public Date Startdate;
}
public class address{
public int addressid;
public int oldcompanyid;
public employee employee;
public Date lastdate;
public Date Startdate;
}
public class company{
public int currentcompanyid;
public string wokingornot;
public address address;
}
public class client{
public int currentcompanyid;
public string wokingornot;
public address address;
}

It's going to look more like this. You will get the whole object graph from the Employee class through Address down to Company and Client classes.
select distinct u from employee u
join u.address uo
left join uo.company tp
left join uo.client mp
where u.lastdate is null and uo.lastdate is null
and (tp.wokingornot= true or mp.wokingornot= true )

Related

Pagination of an complex object into DTO. JPA #Query

I have the following query to take some data regarding two entities in the same time and I receive an error.
#Query(value = "select new base.models.HRTableEntity( yr.user.gid, yr.user.id, yr.user.lastName || ' ' || yr.user.firstName, yr.user.position, yr.user.created,yr.genericField1,yr.genericField2) from YearlyReview yr where yr.year = :yr and yr.user.realDepartment = :dep and yr.user.city = :ct",
countQuery = "select count(yr.id) from YearlyReview yr where yr.year = :yr and yr.user.realDepartment = :dep and yr.user.city = :ct",
nativeQuery = false)
Page<HRTableEntity> getAllTableEntity(Pageable pageRequest, #Param("yr") int year, #Param("dep") String department, #Param("ct") String location);
I call this cunction with default Sort (gid: ASC) and receive the following error
org.hibernate.QueryException: could not resolve property: gid of: base.entities.YearlyReview
Repo interface:
public interface PageableYearlyReview extends CrudRepository<YearlyReview, UUID>
Yearly review have a member (user) of type ApplicationUser and I want to put information into DTO from yr.user.gid into HRTableEntry.gid.
What is the right way to do that ?
EDIT:
function call:
crunRepoYearTable.getAllTableEntity(PageRequest.of(pageNo - 1, pageSize, sort), year, realDepartment, user.getCity())
sort building
sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortedField).ascending() : Sort.by(sortedField).descending();
Entity structure:
public class YearlyReview {
#Id
private UUID id;
private int year;
#OneToOne
private ApplicationUser user;
....
}
public class ApplicationUser {
#Id
private String id;
private String gid;
.....
}
Problem solved:
for sort by gid need to send from the fronted like this user.gid. User is required to refer at AppUser and gid to access information. And change interface like this
public interface PageableYearlyReview extends CrudRepository<ApplicationUser, String>

Linq Attach Child entity to PArent based on common field

I have a parent and child as separate objects. Now I have to combine both based on the join condition.
My entities are
public class Customer
{
private int customerId;
private string customerName;
private List<Order> orders;
}
public class Order
{
private int customerId;
private int orderId;
private string OrderName;
}
Here, customerId is the join field.
I have list of customers, but it has only CustomerId and CustomerName data. It doesn't have Orders ( order object is empty for each customer)
I have _orders as separate object like below.
List<Customer> _customers;
List<Order> _orders;
Now I have to join both and finally, I need _customers object which should have _orders as well.
I have used foreach statement to attach the orders to each customer like below.
_customers.ForEach(c =>
{
c.orders = _orders.Where(o => o.customerId == c.customerId).ToList();
});
But, I want to exclude foreach loop and trying to get through join condition.
Could someone help with this?
Thanks in advance.
You could use GroupJoin to achieve this :
List<Customer> result = _customers.GroupJoin(_orders,
c => c.customerId,
o => o.customerId,
(c, o) => new Customer
{
customerId = c.customerId,
customerName = c.customerName,
orders = o.ToList()
}).ToList();
Test in dotnetfiddle : https://dotnetfiddle.net/OJN480
I hope you find this helpful.

spring-data-jdbc: query entity containing 1-n relation with JOOQ

I am trying to load entities containing a reference to another entity (1-n) with the help of JOOQ (based on spring-data-jdbc).
I'm started extending the spring-data-jdbc-jooq-example.
The adjusted model with the 1-n relation:
#Data
public class Category {
private #Id Long id;
private String name, description;
private AgeGroup ageGroup;
private Set<SubCategory> subCategories;
public Category() {}
public Category(Long id, String name, String description, AgeGroup ageGroup) {
this(id, name, description, ageGroup, new HashSet<>());
}
public Category(Long id, String name, String description, AgeGroup ageGroup, Set<SubCategory> subCategories) {
this.id = id;
this.name = name;
this.description = description;
this.ageGroup = ageGroup;
this.subCategories = subCategories;
}
}
#Data
#AllArgsConstructor
#NoArgsConstructor
public class SubCategory {
private #Id Long id;
private String title;
}
I wrote two queries, one via the #Query-Annotation in the CrudRepository and one with the help of JOOQ in the JooqRepository.
interface CategoryRepository extends CrudRepository<Category, Long>, JooqRepository {
#Query("SELECT * FROM category")
List<Category> findAllWithQuery();
}
public interface JooqRepository {
List<Category> findAllWithJooq();
}
public class JooqRepositoryImpl implements JooqRepository {
private final DSLContext dslContext;
public JooqRepositoryImpl(DSLContext dslContext) {
this.dslContext = dslContext;
}
#Override
public List<Category> findAllWithJooq() {
return dslContext.select()
.from(CATEGORY)
.fetchInto(Category.class);
}
}
(for me both methods should return the same result-set b/c they execute the same query?!)
But my unit-test fails:
#Test
public void exerciseRepositoryForSimpleEntity() {
// create some categories
SubCategory sub0 = new SubCategory(null, "sub0");
SubCategory sub1 = new SubCategory(null, "sub1");
Category cars = new Category(null, "Cars", "Anything that has approximately 4 wheels", AgeGroup._3to8, Sets.newLinkedHashSet(sub0, sub1));
// save category
repository.saveAll(asList(cars));
// execute
List<Category> actual = repository.findAllWithJooq();
List<Category> compare = repository.findAllWithQuery();
Output.list(actual, "JOOQ");
Output.list(compare, "Query");
// verify
assertThat(actual).as("same size of categories").hasSize(compare.size());
assertThat(actual.get(0).getSubCategories()).as("same size of sub-categories").hasSize(compare.get(0).getSubCategories().size());
}
with
java.lang.AssertionError: [same size of sub-categories]
Expecting actual not to be null
As you can see in the following output the sub-categories queried by JOOQ will not be loaded:
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== JOOQ ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=null)
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== Query ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=[SubCategory(id=1,
title=sub0),
SubCategory(id=2,
title=sub1)])
This is the used database-shema:
CREATE TABLE IF NOT EXISTS category (
id INTEGER IDENTITY PRIMARY KEY,
name VARCHAR(100),
description VARCHAR(2000),
age_group VARCHAR(20)
);
CREATE TABLE IF NOT EXISTS sub_category (
id INTEGER IDENTITY PRIMARY KEY,
title VARCHAR(100),
category INTEGER
)
In the JOOQ variant, JOOQ does the conversion from ResultSet to object instances. Since JOOQ doesn't know about the interpretation of aggregates as it is done by Spring Data JDBC it only hydrates the Category itself, not the contained Set of SubCategory.
Spring Data JDBC on the other hand interprets the structure of the Category and based on that executes another statement to load the subcategories.

Spring data Specification join and group by query

I have a class and need to get the max version of each setting from database.
#Table(name = "SETTINGS")
class SettingsEntity {
String id;
int version;
String name;
boolean is_deleted;
}
following is the query that i want to execute
Select s.id, s.version, s.name from SETTINGS as s
join (select id, max(version) as version from SETTINGS group by id) as r
on(s.id = r.id and s.version = r.version) where s.is_deleted = false;
I have a specification that needs to run this query.
public class SettingsQuerySpec implements Specification<SettingsEntity>
{
#Override
public Predicate toPredicate(Root<SettingsEntity> settingsEntityRoot, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder)
{
// how to write the query in specification.
}
}

Spring Data JPA map the native query result to Non-Entity POJO

I have a Spring Data repository method with a native query
#Query(value = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", nativeQuery = true)
GroupDetails getGroupDetails(#Param("userId") Integer userId, #Param("groupId") Integer groupId);
and I'd like to map the result to Non-Entity POJO GroupDetails.
Is it possible and if so, could you please provide an example ?
I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping is inconvienient and makes your code ugly :).
An example right from spring data JPA source code:
public interface UserRepository extends JpaRepository<User, Integer> {
#Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
public static interface NameOnly {
String getFirstname();
String getLastname();
}
}
You can also use this method to get a list of projections.
Check out this spring data JPA docs entry for more info about projections.
Note 1:
Remember to have your User entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname() might return value of last name et cetera).
Note 2:
If you use SELECT table.column ... notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):
#Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
But this works fine:
#Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
In case of more complex queries I'd rather use JdbcTemplate with custom repository instead.
Assuming GroupDetails as in orid's answer have you tried JPA 2.1 #ConstructorResult?
#SqlResultSetMapping(
name="groupDetailsMapping",
classes={
#ConstructorResult(
targetClass=GroupDetails.class,
columns={
#ColumnResult(name="GROUP_ID"),
#ColumnResult(name="USER_ID")
}
)
}
)
#NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
and use following in repository interface:
GroupDetails getGroupDetails(#Param("userId") Integer userId, #Param("groupId") Integer groupId);
According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using #NamedNativeQuery, #SqlResultSetMapping and #ConstructorResult you should be able to achieve that behaviour
I think Michal's approach is better. But, there is one more way to get the result out of the native query.
#Query(value = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", nativeQuery = true)
String[][] getGroupDetails(#Param("userId") Integer userId, #Param("groupId") Integer groupId);
Now, you can convert this 2D string array into your desired entity.
You can write your native or non-native query the way you want, and you can wrap JPQL query results with instances of custom result classes.
Create a DTO with the same names of columns returned in query and create an all argument constructor with same sequence and names as returned by the query.
Then use following way to query the database.
#Query("SELECT NEW example.CountryAndCapital(c.name, c.capital.name) FROM Country AS c")
Create DTO:
package example;
public class CountryAndCapital {
public String countryName;
public String capitalName;
public CountryAndCapital(String countryName, String capitalName) {
this.countryName = countryName;
this.capitalName = capitalName;
}
}
This is my solution for converting to Map and then to custom Object
private ObjectMapper objectMapper;
public static List<Map<String, Object>> convertTuplesToMap(List<?> tuples) {
List<Map<String, Object>> result = new ArrayList<>();
tuples.forEach(object->{
if(object instanceof Tuple single) {
Map<String, Object> tempMap = new HashMap<>();
for (TupleElement<?> key : single.getElements()) {
tempMap.put(key.getAlias(), single.get(key));
}
result.add(tempMap);
}else{
throw new RuntimeException("Query should return instance of Tuple");
}
});
return result;
}
public <T> List<T> parseResult(List<?> list, Class<T> clz){
List<T> result = new ArrayList<>();
convertTuplesToMap(list).forEach(map->{
result.add(objectMapper.convertValue(map, clz));
});
return result;
}
public static class CustomDTO{
private String param1;
private Integer param2;
private OffsetDateTime param3;
}
public List<CustomDTO> doSomeQuery(){
Query query = entityManager.createNativeQuery("SELECT param1, param2 param3 ... ", Tuple.class);
return parseResult(query.getResultList(), CustomDTO.class);
}
Use the default method in the interface and get the EntityManager to get the opportunity to set the ResultTransformer, then you can return the pure POJO, like this:
final String sql = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = ? WHERE g.group_id = ?";
default GroupDetails getGroupDetails(Integer userId, Integer groupId) {
return BaseRepository.getInstance().uniqueResult(sql, GroupDetails.class, userId, groupId);
}
And the BaseRepository.java is like this:
#PersistenceContext
public EntityManager em;
public <T> T uniqueResult(String sql, Class<T> dto, Object... params) {
Session session = em.unwrap(Session.class);
NativeQuery q = session.createSQLQuery(sql);
if(params!=null){
for(int i=0,len=params.length;i<len;i++){
Object param=params[i];
q.setParameter(i+1, param);
}
}
q.setResultTransformer(Transformers.aliasToBean(dto));
return (T) q.uniqueResult();
}
This solution does not impact any other methods in repository interface file.
USE JPA PROJECTIONS
In your case it may be desirable to retrieve data as objects of customized types. These types reflect partial views of the root class, containing only properties we care about. This is where projections come in handy.
first declare Entity as #immutable
#Entity
#Immutable
public class Address {
#Id
private Long id;
set your Repository
public interface AddressView {
String getZipCode();
}
Then use it in a repository interface:
public interface AddressRepository extends Repository<Address, Long> {
#Query("EXEC SP_GETCODE ?1")
List<AddressView> getAddressByState(String state);
}
If you are looking for running a custom SQL query in spring boot with #repository and #service structures. Please have a look.
https://stackoverflow.com/a/71501509/4735043
You can do something like
#NamedQuery(name="IssueDescriptor.findByIssueDescriptorId" ,
query=" select new com.test.live.dto.IssuesDto (idc.id, dep.department, iss.issueName,
cat.issueCategory, idc.issueDescriptor, idc.description)
from Department dep
inner join dep.issues iss
inner join iss.category cat
inner join cat.issueDescriptor idc
where idc.id in(?1)")
And there must be Constructor like
public IssuesDto(long id, String department, String issueName, String issueCategory, String issueDescriptor,
String description) {
super();
this.id = id;
this.department = department;
this.issueName = issueName;
this.issueCategory = issueCategory;
this.issueDescriptor = issueDescriptor;
this.description = description;
}

Resources