I am using hibernate 4 and Spring 3.
I have 5 tables and each table is mapped with 1 entity class.Now if I have to select columns from 1 table than i will do below :
String hql = "from Employee E";
Query query = session.createQuery(hql);
List results = query.list();
This value in this result will be of type EmployeeEntity.
Or I can use Criteria as well.
Now my requirnment is that I have to get the result from all 5 tables.1-2 columns from each table.
Earlier it was one 1 table so i was getting one entity , now I am getting results from 5 tables so how to map it in entity.
List results1 = query.list(); // considering select and getting 6 columns in results with diffenent tables.
Now how to iterate this result1.
I hope you got my question.
You can use Result Set Transformer of Query:
Say you have 4 columns from different tables like tab1col,tab2col,tab3col,tab4col.
Create a 'POJO' as follows
class MyClass
{
private Integer tablcol;
private Integer tab2col;
private Integer tab3col;
private Integer tab4col;
// getter and setters
}
Following way you can transform you result set:
List<MyClass> myClassList=query.setResultTransformer(Transformers.aliasToBean(MyClass.class)).list();
Note: query should contain a result set(something like cursor in oracle).
Related
I use hibernate. There are entries in the database (category), I display these categories on the page, without outputting their id only names. After I create the product, this product should have a connection with the derived categories (with one of them). And I have a question at this point. How can I save an object by making a query with a search by category name and save? Without making 2 requests.
public void save(Products products,String category){
Criteria criteria = session.getCurrentSession().createCriteria(Categories.class);
criteria.add(Restrictions.eq("category_name", category));
Categories resCat =(Order) criteria.uniqueResult();
products.setCategor(resCat);
session.getCurrentSession().save(products);
//This method is not suitable...
}
I need this in the form of hibernate:
INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT table2.column1, table2.column2, 8, 'some string etc.'
FROM table2
WHERE table2.category_name = blablabla;
Basically if we want to query specific columns, we do this:
Query query =
session.createQuery("SELECT tr.review from TravelReview as tr");
List<String> reviews = query.list();
And if we want the original object (TravelReview) instead of List of String, we do this:
String QUERY = "SELECT new City(tr.title, tr.review ) from TravelReview as tr";
List<City> cities = session.createQuery(QUERY).list();
I found it very troublesome to purposely create a Java constructor for the purpose above. (It will end up I have many constructors for this.)
Is there a way to map the selected columns automatically and return the original object (TravelReview), only the attributes that match the selected columns have values, the rest of the attributes will be null (or default value)? Basically something like Spring JdbcTemplate BeanPropertyRowMapper which is very useful and convenient.
What I want to achieve:
Select a susbset of entities that have a property value that exists in a List of values. This list is returned by another Query.
In plain SQL, this can be easily achieved with subqueries. This is the Criteria query that returns the relevant values:
DetachedCriteria subq = DetachedCriteria.forClass(MyClass.class)
.setProjection(
Projections.projectionList()
.add(Projections.alias(Projections.max("interestingVal"), "interestingVal"))
.add(Projections.groupProperty("someval1"))
.add(Projections.groupProperty("someval2"))
.add(Projections.groupProperty("someval3"))
);
I would then like to select the entities that have a value of interesting_val that was returned by the above query. Like so:
List<MyClass> resultList = sessionFactory.getCurrentSession().createCriteria(MyClass.class)
.add(Subqueries.propertyIn("interestingVal", subq))
.list();
Unfortunately, the subq subquery returns a List of Object-arrays with length 4, since I have 4 Projection values. All projection values seem to be automatically added to the SELECT clause. This results in an
SQLSyntaxErrorException: ORA-00913: too many values.
How can I either tell my second Criteria query to only use the first element in the Object array or only retrieve the first column in my subquery?
Instead of propertyIn try propertiesIn.
String[] vals = new String[]{"interestingVal", "someval1", "someval2", "someval3"};
List<MyClass> resultList = sessionFactory.getCurrentSession().createCriteria(MyClass.class)
.add(Subqueries.propertiesIn(vals, subq))
.list();
I have using the Native Query in JPA Repository and my query is as:
select u.*, max(a.version_no) as versionNo from users u left join andother_table a on u.id=a.user_id where u.title='abc' group by id;
from my Query i get the "versionNo" which is not mapped to mu user modal.I have put this also in our user modal like as
#Transient
private String versionNo;
with is getter/setter.but in view i will get versionNo is null.
Please help me.
It is null because you annotated it as #Transient, so it is not populated with DB values. You can execute the query without mapping the results directly to your class, and populate the class manually (the query will return a list of Object[]). Other than this, I'm not aware of any alternatives (because of #Transient).
List<Object[]> results = session.createNativeQuery("select max(a.version_no) as versionNo, u.* from users u left join andother_table a on u.id=a.user_id where u.title='abc' group by id").list();
List<MyClass> myClasses = new ArrayList<MyClass>();
for (Object[] result : results) {
MyClass mc = new MyClass();
...
mc.setVersionNo(result[0]);
mc.setSomethingElse(result[1])
...
myClasses.add(mc);
}
Each entry in results list is an object array representing a row returned by native query. Columns are ordered as you select them, so if you put versionNo in the first place in SELECT clause, it will be available with result[0].
Below is the HQL query I'm using :
Session ssn=HibernateSessionFactory.openSession();
Query query = ssn.createQuery("from TUIDInfo e where e.id = :cred_id ");
query.setParameter("cred_id",cred_id);
List list = query.list();
My table contains around 20 entries matching the cred_id but this query only returns the last row in the table. Why is this so ? The query.list().size() attribute is always 1 even though there are lot more entries.