Retrieving values of a specific field in Hibernate - java

Consider a class:
class Employee{
Integer empId,
//many other fields
}
I need a DAO method as shown below
List<Integer> getAllEmployeeIds(){
//??
}
I dont want List<Employee> and (NEW EDIT) Set<Intger>
How can i do that in hibernate?Am using hbm files for mapping

Like this. Also, I recommend use querydsl to make it type-safe.
List<Integer> getAllEmployeeIds(){
return (List<Integer>)createQuery("select e.empId from Employee e").list();
}

use an hql query and do something like
String hql = "select E.empId from Employee E";
Query query = session.createQuery(hql);
List<Integer> ids = query.list();
follow the documentation from here.

Related

Spring JPA repository JPQL query using a collection of objects

let's say I have the next entity or object:
class Person {
BigInteger cardNumber;
String name;
int age;
Address address;
}
Then, I have a List<Person> and I want to find the youngest person based on the cardNumber and name. So, I'd like to write a query similar to this:
#Query("SELECT p FROM Person p WHERE p.cardNumber = :myPerson.cardNumber AND p.name LIKE :myPerson.name ORDER BY p.age ASC")
public List<Person> find(#param("myPerson") List<Person> personList);
My problem is that I'm not so sure how to tackle this, and what approach to use. I've tried passing two collections, List<String> names and List<BigInteger> cardNumbers and the query was something like this:
#Query("SELECT p FROM Person p WHERE p.cardNumber IN (:cardNumbers) AND p.name IN (:names) ORDER BY p.age ASC")
public List<Person> find(#param("cardNumbers") List<BigInteger> cardNumbers, #param("names") List<String> names);
The problem, I need to use the name and the cardNumber as a single value to compare because, they both work as a primary key. I tried to CONCAT(name, cardNumber) and pass to the method a list of strings with the name.concat(cardNumber.toString(()) value but, I found that the JPQL turns the BigInteger in a number like this 1.00 so, to make it work I need to do something like this name.concat(cardNumber.toString(() + ".00"). That way, it works but, I can't hardcode that mapping from BigInteger to String.
Any advice is appreciated. I just want to find a way to pass the collection of the object rather than concatenate those strings in my code and then pass them to the query method.
Thank you.

selecting distinct ids from a table through hibernate

I have the below pojo which contain many attributes and corresponding setters and getters
public class TOAAarty
{
protected long id;
private long version;
//corresponding setters and getters
}
now i have fire the below query which bring distinct records from the data base
select distinct(id) from toa_arty // so this query bring the distincr ids's
now in the similar fashion i want to rite HQL for this in hibernate to achieve the same as above query so what i have tried is that basically there will be a method which will populate the list with the ids as output
so what i have tried is shown below please advise is it correct and is there any other better approach to achieve the same
public List<Long> findDistinctRrokerIds()
{
Criteria query = session.createCriteria(TOAAarty.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("id"));
query.setProjection(Projections.distinct(proList));
return (List<Long>) criteria.list(); query.list();
}

spring-data #Query mapping result issue

I've created a Repository that extends CrudRepository,
this repository has a method with an #Query notation:
Code:
#Query("select itemType, count(*) as count from Item where User_id = :userId group by itemType")
List<Map<String, Long>> countItemsForUser(#Param("userId") Long userId);
The issue I'm having is that this return a ArrayList of Object(s) and not a List of Map.
I've read somewhere that JPA can't return a Map so that's why I stuff the result in a List>.
I don't know what's the best way to work around this issue or to quickly access the result data.
I've tried casting but that didn't work out either:
for(Object item: items) {
Map<String,Long> castedItem = (HashMap<String,Long>)item;
}
See this example in official documentation of Hibernate.Here
for (Object item:items) {
Object[] tuple = (Object[]) item;
String itemType = (String)tuple[0];
Long count = (Long) tuple[1];
}
Most simple way is to use interface. To let Spring wire query alias
to the interface getter. Example can be found here: https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions
also there is #SqlResultSetMapping. See:
JPA- Joining two tables in non-entity class

What will be the Criteria for following SQL?

Can any one help me out with Criteria for following query :
SELECT * From TableA Inner Join TableB On TableA.ID=TableB.ID
I am trying with the following Criteria
Criteria criteria = session.createCriteria(TableA.class);
criteria.setFetchMode("TableB", FetchMode.JOIN);
The above criteria retrives both the table data.
Also if I need only specific columns from TableA how will the criteria Change ?
Thanks for your time.
Edit: TableA has one-to-many relationship with TableB.
Question doesn't make sense. In hibernate, the 2 Tables should actually be entities in which case they would have a relationship between them. Are you trying to randomly join 2 tables and get a result back? If so you have to use sql and use a ResultTransformer to convert the result into objects.
private ResultTransformer getResultsTransformer()
{
ResultTransformer transformer = new AliasToBeanResultTransformer(
MyResultBean.class) {
#Override
public Object transformTuple(Object[] values, String[] aliases)
{
MyResultBean row = new MyResultBean();
for (int i = 0; i < aliases.length; i++)
{
row.set(aliases[i], values[i]);
}
return (row);
}
};
return transformer;
}
Call this as follows:
Query q = session.createSQLQuery(sql);
q.setResultTransformer(getResultsTransformer());
List<MyResultBean> list = q.list();
UPDATE: If Table A has a 1-to-Many with Table B, then I find it easiest to use Alias
Criteria criteria = getSession().createCriteria(TableA.class);
criteria.createAlias("tableB","b");
criteria.add(Restrictions.eqProperty("id", "b.id");
criteria.list();
I hope this helps. Regards,
With JOIN, you need to indicate to Hibernate that you only want the "root entity", whcih is tableA. Add the following to your code:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Select non-entities with JPA?

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?
I have a non-entity class that wraps two entities:
class Wrap{
Entity1 ent1;
Entity2 ent2
}
#Entity
class Entity1{
...
}
#Entity
class Entity2{
...
}
How can I do something like that?
Query q = entityManager.createNativeQuery("native select here");
List<Wrap> list = q.getResultList();
Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?
No. Native queries can return entities only (if you tell them to do so by passing the resultClass or a resultSetMapping to the createNativeQuery method; if you don't, you will get collections of raw data).
In JPQL, you can use constructor expressions (SELECT NEW...) whith a non-entity constructor. But this is not supported for native queries, you'll have to do it manually.
JPA native query without entity - especially with complex queries (recursive, multiple joins, etc.) ?
This worked for me, but it's hibernate specific :
import org.hibernate.transform.Transformers;
Query query = entityManagerFactory.createEntityManager().createNativeQuery(SQL);
// Transform the results to MAP <Key, Value>
query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("myNamedParam", myParam);
List<Map<String, Object>> list = query.getResultList();
for (Map<String, Object> map : list) {
System.out.println(map);
}
cf. https://www.programmerall.com/article/89371766511/
I think I found the solution.
There is a way to use the NEW keyword in constructing the query.
What I did to resovle this issue :
public List<ProductType> getProductByName(String productName) {
String sqlQuery = "select DISTINCT **NEW** project1.ProductType(o.name, o.revision) from Lhproduct o where o.name = :prodname";
Query qry = getEntityManager().**createQuery(sqlQuery);**
qry.setParameter("prodname",productName);
return qry.getResultList();
}
The ProductType is a non-entity object, a simple plain object implementing Serialiabale. But you need to define the appropriate constructor.
Happy coding :-)
Thanks and Regards,
Hari

Categories

Resources