I have a method like below
public List<String> getSimilarResourceNames(String resourceName){
String searchString = "%"+resourceName+"%";
Session session = getSession();
Criteria criteria = session.createCriteria(Resource.class);
criteria.add(Restrictions.like("name", searchString));
return criteria.list()
}
This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?
Use Projection, you can find examples in Hibernate documentation.
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:
Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
fullnames.add(row[0]);
}
I hope this will help you.
Related
I understand some might simply answer this question with "Why didn't you just Google it"... But I did, and the more I researched this the more confused I got. I'm trying to query my database with Hibernate, the query has a 'where' clause.
Now creating a database entry is easy enough, in the case where I have a 'User' class, I simply do this:
// Gets a new session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
// Creates a new User object
User user = new User("John", "p#55w0rd*", "john#doe.com");
// Save and commit
session.save(user);
session.getTransaction().commit();
But what do I do when I what to for instance
select * from Users where id = '3';
My Google searches pointed to something called HQL, which makes me wonder why I couldn't of just used straight JDBC then. Also it doesn't seem very object oriented. And then there's something like
session.createCriteria(.......
But I'm not sure how to use this.. Any help? Thanks guys.
When you use Native Query (non HQL ) you need to tell hibernate explicitely to handle it like below :
In below query createSQLQuery is special function to handle native sql's
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(User.class);
query.setParameter("employee_id", 3);
List<User> results = query.list();
This can be done using criteria as well for that following is good starting point:
Criteria criteria = sess.createCriteria( User.class);
List<User> users= criteria.list();
http://www.developerhelpway.com/framework/hibernate/criteria/index.php
First of all, you need a hibernate.cfg.xml which contains properties for hibernate. This is e.g url, username and password, the driver and dialect. This file is placed in a package called resources.
You have to choose between using Hibernate Annotations example
or using hbm.xml files example
This is how you tell hibernate what your database is like. It wil automatically create queries for you based on how you annotates or defines in e.g user.hbm.xml.
Create a HibernateUtil.java class which holds the session factory.
You can fetch data from the database with
Criteria crit = getSessionFactory().getCurrentSession().createCriteria(User.class);
Example using queries:
List<?> hibTuppleResultList = currentSession.createQuery(
"from Person p, Employment e "
+ "where e.orgno like ? and p.ssn = e.ssn and p"
+ ".bankno = ?")
.setString(0, orgNo).setString(1, bankNo).list();
for (Object aHibTuppleResultList : hibTuppleResultList)
{
Object[] tuple = (Object[]) aHibTuppleResultList;
Person person = (Person) tuple[0];
hibList.add(person);
}
In the end all I really wanted was to know that if you don't want to use HQL you get something called 'Criteria Queries', and that in my case I'd do something like this:
Criteria cr = session.createCriteria(User);
cr.add(Restrictions.eq("id", 3));
List results = cr.list();
Me: "Thanks!"
Me: "No problem :)"
PS - we can really delete this question.
Query q = session.createQuery("from User as u where u.id = :u.id");
q.setString("id", "3");
List result = q.list();
Query with Criteria:
Criteria cr = session.createCriteria(User.class);
List results = cr.list();
Restrictions with Criteria:
Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq("id", 3));
// You can add as many as Restrictions as per your requirement
List results = cr.list();
You could also use it like this
List results = session.createCriteria(User.class).add(Restrictions.eq("id", 3)).list();
Some example for Crieteria Rsetriction query
Criteria cr = session.createCriteria(Employee.class);
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));
// To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));
// To get records having fistName starting with zara cr.add(Restrictions.like("firstName", "zara%"));
// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));
// To get records having salary in between 1000 and 2000
cr.add(Restrictions.between("salary", 1000, 2000));
// To check if the given property is null
cr.add(Restrictions.isNull("salary"));
// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));
// To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));
// To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));
You can create AND or OR conditions using LogicalExpression restrictions as follows:
Criteria cr = session.createCriteria(Employee.class);
Criterion salary = Restrictions.gt("salary", 2000);
Criterion name = Restrictions.ilike("firstNname","zara%");
// To get records matching with OR condistions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );
// To get records matching with AND condistions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );
List results = cr.list();
I think this will help you
I want to get distinct values from my db.
I have 10 fields in this db, and when i try to use such query:
SELECT DISTINCT (IMIE)FROM `przychodzace`
I get 26 results, but hibernate returns me just 17...
Here is list function:
List<String> list = new ArrayList<String>();
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Criteria criteria = session.createCriteria(PrzychodzaceModel.class);
if (i == 0) {
criteria.setProjection(Projections.distinct(Projections.property("imie")));
criteria.addOrder(Order.asc("imie"));
}
list = criteria.list();
System.out.println(list.size() + "size");
return list;
Have anyone idea how to do it properly, i am trying to correct it for long time.
Thanks in advance.
I think an alternative to your problem would be to use a DAO class with a List method, eg:
public List listMenu() {
String hql = "FROM Menu";
org.hibernate.Query query = session.getCurrentSession().createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(5);
List results = query.list();
return results;
}
i need the hql query that should return the Map as result, I tried hql new map query but it returns the list of map like follows
Session session = sessionFactory.getCurrentSession();
String HQL_QUERY = "select new map(user.id as id, user.fullName as fullName)
from User user";
List<Map<String,String>> usersList = session.createQuery(HQL_QUERY).list();
if this is the only solution then how do i convert a list of map into a single map without looping, because if the query returns more rows then the looping take more time for convertion. Help me.
I would suggest using Criteria and then a result transformer to create a map. Have a look at this for official documentation. This gives you a clue and you can find more samples on net.
Creating a map is not the job of HQL. It's your job. Simply loop over the rows you get from the query:
String hql = "select user.id, user.fullName from User user";
List<Object[]> rows = session.createQuery(hql).list();
Map<String, String> result = new HashMap<>();
for (Object[] row : rows) {
result.put((String) row[0], (String) row[1]);
}
you can use map like below
Query query = session.createQuery("select new map(id,username) from UserDetails");
List<?> idUsernameList=query.list();
Iterator<?> iterator = idUsernameList.iterator();
Map row=null;
while(iterator.hasNext()){
row=(Map)iterator.next();
System.out.println(row);
}
Actually I had one SQL query that runs very fine with mySql database. but, my problem is that I want to write that query in hibernatetemplate query.
My SQL QUERY IS
SELECT * FROM task, dependency WHERE DEPENDENCY_From IN(10,11,12,13)
and I want it to executed by the hibernate template.
How do I to convert this to a HibernateTemplate Query?
If you want to use HibernateTemplate query then below is example of hibernate query but in your case, we need mapping files to see how the entities are associated. Hope below query will help you.
public List<Object[]> getCities(Integer stateId) {
List<Object[]> cityList = new ArrayList<Object[]>();
String query = "select city.cityId,city.cityName from City city where city.state.stateId=?";
Object[] queryParam = {stateId};
cityList = getHibernateTemplate().find(query, queryParam);
return cityList;
}
or
String query="from City";
List<City> cityList = getHibernateTemplate().find(query);
HQL query
Object[] params = {cid,cid};
List list=getHibernateTemplate().find("select S.stateName,C.countryName from State S,Country C where C.countryId=? and S.countryId=?", params);
SQL Query
select S.stateName,C.countryName from State S,Country C where S.countryId=C.countryId;
I would like to implement the following SQL query with Hibernate Criteria:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name
I have tried to implement this with Hibernate Criteria but it didn't work out.
Can anyone give me an example how this can be done with Hibernate Criteria?
Thanks!
Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
You can use the approach #Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
If you have to do group by using hibernate criteria use projections.groupPropery like the following,
#Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;