How to use update query in hibernate - java

hi am very new to hibernate and could anybody plz help me out how to use update query to upadte the record of the table ...i am using like this in dao class
Session ses = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
Query q = ses.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", bean.getEmail());
RegisterPojo pojo = (RegisterPojo) q.list().get(0);
pojo.setUname(bean.getUname());
ses.update(pojo);
tx.commit();
ses.flush();
ses.close();
Hi i have edited my code from this am getting exception as, Could not execute JDBC batch update
thanks in advance

You need to call update on the hibernate session
Observe the following example
Query q = session.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", "Fred#Example.com");
RegisterPojo pojo= (RegisterPojo)q.list().get(0);
pojo.setName("Fred");
session.update(pojo);

Related

How to delete data from mongodb v3.4 with hibernate ogm 5.1.0?

I am only able to retrieve data and insert data in mongo DB v 3.4 using Hibernate OGM 5.1.0.Final. I am not able to perform delete operation or update operations. Can anyone help me out with an example?
This question is a bit vague, I'm not sure if you know how to delete an entity with Hibernate OGM and it's not working (in this case post an example of your code, please) or you don't know how JPA works. I will assume you don't know how to delete entities and add some examples on how to do it.
Using the session:
try ( Session session = openSession() ) {
Transaction transaction = session.beginTransaction();
Hypothesis entity = (Hypothesis) session.get( Hypothesis.class, hyp.getId() );
session.delete( entity );
transaction.commit();
}
Using the EntityManager (JPA):
final EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
Poem poem = em.find( Poem.class, poem.getId() );
em.remove( poem );
em.getTransaction().commit();
}
finally {
em.close();
}
Using the MonogDB CLI API:
try ( OgmSession session = openSession() ) {
Transaction transaction = session.beginTransaction();
String nativeQuery = "db.Poem.remove({ '_id': { '$numberLong': '11' } })";
Query query = session.createNativeQuery( nativeQuery ).addEntity( Poem.class );
query.executeUpdate();
}
About updates, I will leave it to the Hibernate ORM documentation.
If this doesn't answer your question please, try to elaborate more. Test cases are always appreciated.

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();

Hibernate - the second query gives Unknown service requested

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.

Using Hibernate to CREATE SCHEMA in PostgreSQL

All i want is to execute the following SQL on my PostgreSQL server after my Hibernate SessionFactory has been initialized:
CREATE SCHEMA IF NOT EXISTS "fooschema" AUTHORIZATION "foouser";
Currently I am using the following routine:
Session s = factory.withOptions().openSession();
SQLQuery query = s.createSQLQuery(sql);
int res = query.executeUpdate();
// res is 0 and the schema has NOT been created
s.flush();
s.disconnect();
s.close();
The connected user has the permissions to chreate new schemata. So this is a simple question:
What am i doing wrong?
Attachments:
Turning hibernate show_sql on prints the following:
Hibernate:
CREATE SCHEMA IF NOT EXISTS "fooschema" AUTHORIZATION "foouser";
Try setting property
<property name="hbm2ddl.auto" value="create"/>
in hibernate config
The solution for my problem (Thanks to #a_horse_with_no_name)
Session s = factory.withOptions().openSession();
Transaction tx = s.beginTransaction();
SQLQuery query = s.createSQLQuery(sql);
int res = query.executeUpdate();
tx.commit();

How to use Delete query in Hibernate

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.

Categories

Resources