Convert List<Tuple> to List<Bean> - java

I don't want to show all my attributes on a table, so I'd like to select only a few columns and then map their values to a bean, something similar to Hibernate's Transformers.aliasToBean(T.class), but using JPA and Criteria.
I'm able to get a List<Tuple>, how could I transform it into a List<T>?
As the the title says, is it possible?

Within JPQL/Criteria queries you can provide arguments to an objects constructor within the query so that the query returns those objects for you. For example:
"SELECT new package.BeanClass(e.attribute1, e.attribute2) from Entity e"
With native SQL queries, if you are using JPA 2.1, you can use ConstructorResult to build the same instances:
http://en.wikibooks.org/wiki/Java_Persistence/Querying#ConstructorResult_.28JPA_2.1.29
But if you are not able to use Jpa 2.1, you will need a provider specific solution such as http://onpersistence.blogspot.com/2010/07/eclipselink-jpa-native-constructor.html

Related

How to retrive/display column names and its data based on dynamic query in spring data jpa?

How to retrieve/display column names and its data based on dynamic query in spring data jpa?
Example dynamic query be like
Select empid, empname, address from emp (or)
Select productiD, pname, price, pquantity from Product
I don't want to map entity just need to display data?
For a completely dynamic query Spring Data JPA doesn't offer any special support, so in order to integrate it into your repository you'll need to define a custom method.
Since you only want a Map anyway the easiest way might be to use a SQL query, execute it with a JdbcTemplate and have a simple ResultSetExtractor that inserts the values from the ResultSet into a Map.
If you want to utilise the mapping information of JPA you might construct a query using the Criteria API where you explicitly specify all the columns you want and specify Tuple as target type.

How to map columns in hibernate with class attributes?

My problem statement is :- I want to call a stored procedure in hibernate and i want to map each column to class attributes after performing certain operations on the column returned by the stored procedure.. As any hibernate query return a list of object instead of resultset.. so how can i do it in hibernate...
I know in spring we can do it using jdbcTemplate Map row concept easily but I want to use Hibernate only..
More details can be found out in my prev question:-
Alternative to NamedParameterJDBC template row mapper in Hibernate
There are times we have a class, we would like to fill with data according the data returned from a query. The class is a simple POJO and not an Hibernate entity, so Hibernate won’t recognize this class. This can be done in Hibernate by using Transformers.
(UserActivityStat)hibernateSession.createQuery("select count(*) as totalPhotos from Photo p where p.user = :user").setResultTransformer(Transformers.aliasToBean(UserActivityStat.class)).uniqueResult();
In the above example totalPhotos is a property of Class UserActivityStat which is not a HibernateEntity. Using transformers you can achieve your result.

Hibernate 4 finding record by property

Is there any specific method for finding record from database?
I don't want to use criteria api and load() only fetch data using primary key but what about if i want to find records using other columns? I know it is possible with criteria but want to know is there any other option?
From our discussion in chat. OP was looking for a way to query using combinations of entity fields only known at runtime. I've suggested Criteria - Example Queries.
Sample from official documentation:
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.list();
As far As I know there is no method directly for that ..
You can try using HQL or Native SQL query.
And
In criteria API you need to add Projections to fetch the required properties on POJO's

Programmatic, "non-dynamic" construction of HQL queries within the bounds of the JPA

Example:
List<Object[]> list = em.createQuery(
"SELECT 'Foo', 123 FROM IrcEvent ev", Object[].class).getResultList();
What I don't like in that example:
How do I know the table name? Can't I specify the entity class instead?
How do I know the column name? jOOQ provides auto-completion by creating a DSL from the database schema.
There could be syntax errors everywhere.
What I basically want is something like
entityManager.deleteAll(EntityClass.class);
to delete the rows of an antire table (for example).
JPA 2 Criteria API http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html is for creating type safe queries programmatically, but it does not support deletes

How does setParameterList in hibernate work?

I am having some problem with the setParameterList api of hibernate.
I am trying to pass in a Collection to a SQLQuery and doing an "in" clause search.The records exists in the DB and doing a raw query, I am able to retrieve them or if I just replace them in the same Hibernate SQL like emp.emp_name in ('Joe','John'), I am able to get the desired result set. I am confused as to why would Hibernate fail to replace the Collection in place of the named parameter. Here is the code :
session.createSQLQuery("select emp_id as id from emp where emp.emp_name in (:empNames)")
.addScalar("id",Hibernate.INTEGER)
.setParameterList("empNames",new String[]{"Joe","John"})
.list()
I have looked at the Hibernate Documentation for setParameterList but I am not able to reason out this particular behavior.
I suspect the problem is precisely because you're using createSQLQuery. The single parameter here needs to be changed into multiple parameters in the real SQL, but by using a "raw" query you're telling Hibernate not to mess with the SQL.
Can you use a "normal" Hibernate query instead?
Just remove the parenthesis around the parameter name :
session.createSQLQuery("select emp_id as id from emp where emp.emp_name in :empNames ")
.addScalar("id",Hibernate.INTEGER)
.setParameterList("empNames",new String[]{"Joe","John"})
.list()
I would not suggest to use (N)Hibernate's parameter lists. Query plans in cache are not used when the number of elements in parameter list is different. So it means your query is often hard parsed and compiled. Queries are slower, database load is higher and plan cache is full of plans generated for the same query.

Categories