Combine Hibernate ResultTransformer result with original Hibernate Object - java

Here is what I am trying to do:
1. Send an HQL to populate "User" Hibernate object.
2. Send a native SQL to retrieve a smaller dataset from a very large data column from "User" table.
3. Combine the mapped Hibernate object with the column result from step 2.
I read that ResultTransformer can be used to map the resultset from 2 to a Hibernate entity, which in my case the "User" entity. Is there a way to insert the results of the ResultTransformer mapping to my original User entity?
Here's some example: 1. HQL - From User. We use Hibernate mapping file for User and using Bytecode Enhancement, we set "xmlStringColumn lazy=true". String hql = "FROM User";
List users = session.createQuery(hql).list(); 2. we send a query
List resultXML = s.createSQLQuery(
"XML SQL to get specific data")
.setResultTransformer( Transformers.aliasToBean(User.class))
.list();
User dto =(User) resultWithAliasedBean.get(0); //Will need code to combine the User dto from the SQL to the original

ResultTransformer bundles one to many relationship objects into single object.
For example,
Class A{
Set b=new Hashset();
}
So if you start query from class A and add join on B it will end up in creating multipe objects of A.
ResultTransformer bundles data into single A object.
Can you please post code so we can understand what you are tyring to acheive!!!

Related

Get Data from 2 tables in spring boot jpa

I have one table which has all the api audit information - Table name : api_audit
I have one table which has extra information about every api call - Table name : api_audit_info
Inside api_audit I have primary key as "transaction_id".
I want all the data from api_audit table and some data from api_audit_info table.
I have written a custom query like -
#Query(select c from ApiAudit c INNER JOIN ApiAudiInfo t ON c.transactionId = t.msgId)
But the issue is that the result type that I am getting this way contains only ApiAudit type data.
What shall I do to get data from both the tables. Please help.
Note: I am using JpaRepository as I need paginated data.
I am fairly new to Spring boot and JPA so not sure exactly which direction to look to.
Whenever I need to join data from more than 1 table, I am using Jdbi.
Here you have the official documentation:
Remember to include the required dependencies and configure a bean for Jdbi in your project.
Then I create a repository class, POJO and query with all of the information which I need. For example:
select c.transaction_id as transactionId, t.name as name from ApiAudit c INNER JOIN ApiAudiInfo t ON c.transactionId = t.msgId
Here you have some code samples from official documentation
After you map your data to POJO, you can use
public PageImpl(List<T> content, Pageable pageable, long total)
to return paginated data.
There is a big chance that there is a better solution, but this works for me every time.

Map sql query result to java object(in Non-Entity class) using spring jpa

I want to assign SQL query result to Java object which is in non-entity class.
My query is counting the number of records in Table A mapped to another Table B.
#Query(value="select count(a.id) from table1 a join table2 b on a.id=b.id group by a.id", nativeQuery=true)
Non-Entity class
public class Sample {
//assign query result to count variable
private long count;
// getters and setters
}
A and B are Entity class, I'm selecting specified columns of Entity A and B and including that columns in Sample.class and sending data as JSON on REST call.
Now my question is to assign count result to count variable.
Thanks in advance
How to do a JPQL query using a "group by" into a projection (Non-Entity-Class)?
Scenario you have two tables: User and User_Role and you want to know how many users in your system has the "public" role and how many have the "admin" role (Any other roles too if present).
For example: I want a query that will let me know there are two users that have "public" role and one user has the "admin" role.
Simplest Example:
#Query("SELECT ur.roleName, count(u.id) from User u left join u.userRole ur group by ur.roleName")
List<Object[]> getCounts();
In this case dealing with the result is more complicated then you typically would want. You would have to iterate over both the list and array of Objects.
Query into a projection Example:
#Query("SELECT new com.skjenco.hibernateSandbox.bean.GroupResultBean(ur.roleName, count(u.id)) from User u left join u.userRole ur group by ur.roleName")
List<GroupResultBean> getCountsToBean();
This would give you a List that is much better to work with.
Code Example: https://github.com/skjenco/hibernateSandbox/blob/master/src/test/java/com/skjenco/hibernateSandbox/repository/UserProjectionExampleTest.java

Hibernate query build

Currently i am using the CreateSQLQuery query model to read the data from database using HIbernate. Now, I want to modify my query by using either HQL or Hibernate Criteria. My query looks like as follows.
select concat(d.AREA,' ',d.CITY) as location, a.TRANSFERRED_DATE as ActualTransferDate, concat(c.SCAN_CODE,',',c.SERIAL_NO) as ScanserialCode, c.MODEL_NO as ModelNum, c.ASSET_NAME as AssetName from table_transfer a, table_category b, table_asset c, table_location d where a.ASSET_ID = c.ASSET_ID and b.ASSET_CATEGORY_ID = c.ASSET_CATEGORY_ID and a.TRANSFER_TO_LOCATION=d.LOCATION_ID"
I am not sure how can i can convert this to Hibernate SQL or Criterion based query. Can any one help me?
You can introduce the fields for location and scanserialCode in your entity and mark them as #Formula
e.g.
#Formula("concat(d.AREA,' ',d.CITY)")
private String location;
See an example here or here
Then use join and where in HQL or Hibernate Criteria

OpenJPA inserting into one table data from another table

I am new to OpenJPA
I am trying to insert data into a table some of which comes from another table. Below is the scenario.
Table1: id, app_name, app_version, app_active
Table2: id, app_name, app_version, dev_name, dev_Lastname, dev_shortname,
Pojo1 maps fields to column of table1
Pojo2 maps fields to column of table2
Query:
insert into table2 ("dev_name","dev_lastname","dev_shortname") select t1.app_name, t1.app_version from Table1 t1 where t1.app_name = ?
i dont know how to run this query using Openjpa and how to map these fields to each other in two pojos.
if I use the Query object then what about the pojos?? will they come in use?? I mean will i need to do transaction.save??
Any help with a sample code appreciated.
Your query manipulates data directly in the database while JPA handles the object relationships.
Im not sure what problem you are trying to solve but can you read the Pojo1 convert it to a Pojo2 object that you just save?
Edit:
In you java application first retrieve your Pojo1 from the entity manager with some query.
Then Construct corresponding Pojo2 objects with the fields you want from Pojo1. Then just to entityManager.persist with your new Pojo2 objects.
This is quite complex to perform what you showed could be made in a one line sql statement.

Java-Hibernate-Newbie: How do I acces the values from this list?

I have this class mapped
#Entity
#Table(name = "USERS")
public class User {
private long id;
private String userName;
}
and I make a query:
Query query = session.createQuery("select id, userName, count(userName) from User order by count(userName) desc");
return query.list();
How can I access the values returned by the query?
I mean, how should I treat the query.list()? As a User or what?
To strictly answer your question, queries that specify a property of a class in the select clause (and optionally call aggregate functions) return "scalar" results i.e. a Object[] (or a List<Object[]>). See 10.4.1.3. Scalar results.
But your current query doesn't work. You'll need something like this:
select u.userName, count(u.userName)
from User2633514 u
group by u.userName
order by count(u.userName) desc
I'm not sure how Hibernate handles aggregates and counts, but I'm not sure if your query is going to work at all. You're trying to select a aggregate (i.e. the "count(userName)"), but you don't have a "group by" clause for userName.
If the query does in fact work, and Hibernate can figure out what to do with it, the results you get back will most likely be a raw Object[], because Hibernate will not be able to map your "count(userName)" data into any field on your mapped objects.
Overall, when you get into using aggregates in queries, Hibernate can get a little more tricky, since you're no longer mapping tables/columns directly into classes/fields. It might be a good idea to read up more on how to do aggregates in Hibernate, from their documentation.

Categories

Resources