Hibernate criteria with collections - java

Tags contains tag with field name with value "#tylkoclara".
In first case results has size 1 which is expected result
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
List<Tag> results = new ArrayList<Tag>();
Criteria criteria = session.createCriteria(Tag.class);
criteria.add(Restrictions.eq("name", "#tylkoclara"));
results = criteria.list();I
But if I try to use whole collection as criteria, result's size is 0
public static List<Tag> filterTags(List<Tag> tags) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Tag.class);
List<Tag> results = new ArrayList<Tag>();
for(Tag tag : tags) {
criteria.add(Restrictions.eq("name", tag.getName()));
}
results = criteria.list();
I have no ideas why is that happening

By adding your Restrictions in a loop like this, you are creating AND condition instead of OR condition. And since no tag has multiple different names, 0 results will be returned.
You need to create OR condition, for example like this (I've omitted the parts of your code dealing with session creation, etc to keep the example shorter):
public List<Tag> filterTags(List<Tag> tags) {
Criteria criteria = session.createCriteria(Tag.class);
Disjunction disjunction = Restrictions.disjunction();
for (Tag tag : tags) {
disjunction.add(Restrictions.eq("name", tag.getName()));
}
criteria.add(disjunction);
return criteria.list();
}

Related

Hibernate query for selecting values from a table with input from pathvariable

I have a rest api Spring MVC,database oracle sql developer and I am using hibernate for mapping.
I have a table Iteration.My code is:
#RequestMapping(value="{userid}",method=RequestMethod.GET)
public #ResponseBody List<IterationInfo> getIterationInfoInJSON(#PathVariable int userid)
{
Configuration con = new Configuration();
con.configure("hibernate.cfg.xml");
SessionFactory SF = con.buildSessionFactory();
Session session= SF.openSession();
Transaction TR = session.beginTransaction();
Query query=session.createQuery("from IterationInfo");
List<IterationInfo> listiterationinfo=query.list();
session.close();
SF.close();
return listiterationinfo;
}
I want to fire a query select * from IterationInfo where userid=(The userid I get from the path variable).
Like from (#pathVariable int userid)
What query should I use in my class??
Query query=session.createQuery("from IterationInfo WHERE userId=:userId");
query.setParameter("userId", userid);
IterationInfo iterationinfo=query.uniqueResult(); // Returns null if not found
I cannot see your IterationInfo class, so I'm not 100% sure on the name of the field there (I assumed userId).
Try this this may help you.
String hql = "from iterationInfo WHERE userId=:userId";
Query query = session.createQuery(hql);
query.setParameter("userId", userid);
List<IterationInfo> iterationinfolist = query.list();

How to use Contains in Hibernate

session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql ="from CustomObjectId where CONTAINS(fileName,fileName)";
Query query = session.createQuery(hql);
query.setParameter("fileName", fileName);
List file=query.list();
tx.commit();
How can I search CONTAINS?
You need to use IN clause as shown below:
session = sessionFactory.openSession();
String hql =" from CustomObjectId c where c.fileName in :fileName";
Query query = session.createQuery(hql);
query.setParameter("fileName", fileName);
List file=query.list();
Also, you DO NOT need a transaction (explicitly) to only READ from database. So, just remove Transaction tx = session.beginTransaction(); and tx.commit(); lines.
You can do that with Hibernate Criteria.
String fileNames[] = {"fileName1", "fileName2"};
session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(CustomObjectId.class);
criteria.add(Restrictions.in("fileName ", fileNames));
List list = criteria.list();

Hibernate Criteria searching request with One to Many relationship

I've tried to do it like:
session = HibernateUtil.getSessionFactory().openSession();
Criteria cr = session.createCriteria(Car.class);
cr.createAlias("vendor", "vendor");
cr.add( Restrictions.eq("vendor.name", input));
results = (List<Car>) cr.list();
And also like:
session = HibernateUtil.getSessionFactory().openSession();
Criteria cr = session.createCriteria(Car.class);
cr.createCriteria("vendor").add(Restrictions.eq("name", input));
results = (List<Car>) cr.list();
Both realizations just return all data, not specified with search query.
In the Car Class I've got relationship:
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="id_vendor", nullable=false)
public Vendor getVendor() {
return this.vendor;
}
And also I've got thename column at the Vendor class at which I'm trying to search.
So how possibly I could do such search request?
Thanks.
You need to assign your criteria back to the original object.
The reason you get all the cars back is because the line of code adding your vendor into the query creates you a new criteria object which you are then not using.
Change:
session = HibernateUtil.getSessionFactory().openSession();
Criteria cr = session.createCriteria(Car.class);
cr.createCriteria("vendor").add(Restrictions.eq("name", input)); //Does nothing
results = (List<Car>) cr.list();
into this:
session = HibernateUtil.getSessionFactory().openSession();
Criteria cr = session.createCriteria(Car.class);
cr = cr.createCriteria("vendor").add(Restrictions.eq("name", input));
results = (List<Car>) cr.list();
And it should work.
if you wont get unique result of Car.class you nedd set ResultTransformer
Criteria cr = session.createCriteria(Car.class);
cr.createAlias("vendor", "vendor");
cr.add( Restrictions.eq("vendor.name", input));
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
results = (List<Car>) cr.list();

hibernate select distinct values order by one value

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;
}

How do I stop hibernate returning multiple instances when using "join" fetch mode?

Given the following I am trying to force the child collection (countryData) to be loaded when I perform the query, this works however I end up with duplicates of the Bin records loaded.
public Collection<Bin> getBinsByPromotion(String season, String promotion) {
final Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
return (List<Bin>) session.createCriteria(Bin.class).
setFetchMode("countryData", FetchMode.JOIN).
add(Restrictions.eq("key.seasonCode", season)).
add(Restrictions.eq("key.promotionCode", promotion)).
add(Restrictions.ne("status", "closed")).
list();
} finally {
session.getTransaction().commit();
}
}
I don't want the default (lazy) behavior as the query will return ~8k records thus sending 16k additional queries off to get the child records.
If nothing else I'd prefer.
select ... from bins b where b.seasonCode = ?
and b.promotionCode = ?
and b.status <> 'Closed';
select ... from binCountry bc where bc.seasonCode = ?
and bc.promotionCode = ?;
you can use CriteriaSpecification.DISTINCT_ROOT_ENTITY;
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

Categories

Resources