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();
Related
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();
I'm trying to understand better how Hibernate works...
I've a problem I cannot resolve.
When the application starts, it makes a query
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
int result;
String query = "SELECT count(*) as posti_disponibili from occupazione t inner join ";
query += "(select id_posto_park, max(date_time) as MaxDate from occupazione group by id_posto_park) tm on ";
query += "t.id_posto_park = tm.id_posto_park and t.date_time = tm.Maxdate and t.isOccupied = 0";
BigInteger bi = (BigInteger) session.createSQLQuery(query).uniqueResult();
result = bi.intValue();
HibernateUtil.shutdown();
At the end I close the current session.
Then, after it, I have a second query to be accomplished:
I open a new session (the first one was closed with the method HibernateUtil.shutdown();)
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Client client = new Client();
client.setIdClient(clientId);
String queryString ="from it.besmart.models.Client where clientId = :c)";
List<?> list = session.createQuery(queryString).setProperties(client).list();
but I got, now,
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.cfg.Settings.getRegionFactory(Settings.java:300)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1322)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:677)
at it.besmart.parkserver.SocketClientHandler.run(SocketClientHandler.java:78)
at java.lang.Thread.run(Thread.java:744)
I cannot understand why, I closed the first session, but then opened a new one..
Is it correct to close the session on each query
EDIT
I'm trying to solve this problem, but with no result.
Now I have the first select query, which goes well. It's at the startup of the application.
try {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String query = "SELECT count(*) as posti_disponibili from occupazione t inner join ";
query += "(select id_posto_park, max(date_time) as MaxDate from occupazione group by id_posto_park) tm on ";
query += "t.id_posto_park = tm.id_posto_park and t.date_time = tm.Maxdate and t.isOccupied = 0";
BigInteger bi = (BigInteger) session.createSQLQuery(query).uniqueResult();
result = bi.intValue();
}
I do not commit or flush it.
Then, going up with the application, I have the second query, so I getCurrentSession and try to do the select
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Client client = new Client();
client.setIdClient(clientId);
String queryString ="from it.besmart.models.Client c where c.clientId = :c";
logger.debug(queryString);
// logger.debug(session);
Query theQuery = session.createQuery(queryString).setProperties(client);
List<?> list = theQuery.list();
The application stops, nothing comes out, I don't know what's going on also because I cannot setup hibernate to log with pi4j...
Is there something wrong in how I use hibernate sessions?
If you use sessionFactory.getCurrentSession(), you'll obtain a "current session" which is bound to the lifecycle of the transaction and will be automatically flushed and closed when the transaction ends (commit or rollback).
If you decide to use sessionFactory.openSession(), you'll have to manage the session yourself and to flush and close it "manually".
For more info go to Hibernate transactions.
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();
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'm using Hibernate to delete the records from a table,but this giving an exception, could anyone know how to overcome this problem in the below query?
Session ses = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
Query q = ses.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
RegisterPojo pojo = (RegisterPojo) q.list().get(0);
ses.delete(pojo);
tx.commit();
ses.close();
Why not ?
Query q = ses.createQuery("delete from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
q.executeUpdate();
Learn HQL
Before proceeding please learn more about hql. That reduces large amount of code.