I am new to Hql. I am facing problem in select query. I am actually doing group rename option. For that first I am looking for pericular Id. next if there is no groupname of new groupname then I am updating old groupname. My method is like this.
private void renameGroup(String ogname, String gname , String clientid) {
//Here ogname="group7"
// gname="group8"
System.out.println("Old group name2="+ogname);
Session hSession = HibernateSession.getHibernateSession();
Transaction transaction = hSession.beginTransaction();
String hql= "select groupname from GroupDetails where clientid=:clientid and groupname=:oldGroupName";
Query query = hSession.createQuery(hql);
query.setParameter("clientid", Integer.valueOf(clientid));
query.setParameter("oldGroupName",ogname );
List<Object[]> groupList = (List<Object[]>) query.list(); // This has groupname [group7]
if(!(groupList.isEmpty()))
{
Session hSession2 = HibernateSession.getHibernateSession();
Transaction transaction2 = hSession.beginTransaction();
String hql2= "select groupname from GroupDetails where clientid =:clientid and groupname=:newGname";
Query query2 = hSession2.createQuery(hql2);
query2.setParameter("clientid", Integer.valueOf(clientid));
query2.setParameter("newGname",gname );
List<Object[]> groupList2 = (List<Object[]>) query2.list();//Here it has to be empty so that I can update but it also has [group7]
if(groupList2.isEmpty())
{// So it never come to this block
String hql3="update GroupDetails set groupname=:newGroupName where clientid=:clientid and groupname=:ogname";
Query query3 = hSession.createQuery(hql2);
query3.setParameter("newGroupName", gname);
query3.setParameter("clientid",Integer.valueOf(clientid));
query3.setParameter("ogname",ogname);
int res = query3.executeUpdate();
System.out.println("Command successfully executed....");
System.out.println("Numer of records effected due to update query"+res);
}
}
}
Observe my comments for better understand of my problem. I think problem is in session and transaction. but I am not getting. Please help me to solve this problem. Thank you
Related
I want to delete all those rows from xyz table where id = 1 using hibernate spring.
I have tried following code but its not giving error but not deleting rows -
Session session = (Session) getEm().getDelegate();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
Can you please help me to delete all rows using hibernate query.
Try wrapping your code within a transaction like this:
Session session = (Session) getEm().getDelegate();
Transaction tx = session.beginTransaction();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
tx.commit();
Try
query.setParameter("id", Long.valueOf(1));
if your entity is of type Long (which ideally should be).
Reference: http://www.codejava.net/frameworks/hibernate/hibernate-basics-3-ways-to-delete-an-entity-from-the-datastore
Note: The link is just for your reference.
public void deleteById(Class clazz,Integer id) {
String hql = "delete " + clazz.getName() + " where id = :id";
Query q = session.createQuery(hql).setParameter("id", id);
q.executeUpdate();
}
I have a table by name Person and it has only one row data. I dont want to take it in list(). Can I get the data of Object type. Below is my code snippet
Session session = this.sessionFactory.openSession();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
List<Person> list = query.list();
===================================
I want the above code snippet to work as below:
Session session = this.sessionFactory.openSession();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
Person p = query;
which is throwing error. Please help me out on fixing the issue.
query is result of your session select. query.list() is your results. and you can get with query.list().get(0);
You can cast query list to personList;
List<Person> list = query.list();
return list.get(0);
You can just cast your result to person;
Person p = (Person) query.list().get(0);
need a help to create hibernate query that table is jdwCustomerTlrdRef and it should take all the operation_spec = customer name. the method should return sysId.
Here is the code to review. Please help me i am new to this hibernate query.
public getCustomerTlrdRef(BigDecimal sysId) {
System.out.println("---- getAllCustomerTlrdRef " );
String query = "from JdwCustomerTlrdRef as jdwCustomerTlrdRef where jdwCustomerTlrdRef.operation_spec= '+customer_name+'";
Query q = getSessionFactory().getCurrentSession().createQuery(query);
List<JdwCustomerTlrdRef> customerTlrdRefSysId = q.list();
System.out.println(" List size: " + customerTlrdRefSysId.size());
return customerTlrdRefSysId;
}
This should work.
String query = "from JdwCustomerTlrdRef jdwCustomerTlrdRef where jdwCustomerTlrdRef.operation_spec= '+ customer_name +'";
Otherwise if you want to pass the parameter later in your code then do it this way.
String query = "FROM JdwCustomerTlrdRef jdwCustomerTlrdRef WHERE jdwCustomerTlrdRef.operation_spec = :customer_name"
then in your code you can pass the parameter this way.
query.setParameter("customer_name", theCustomerNameParameter);
Hi this my java code here am using hibernate to check whether this email id and password exist in db or not could anybody plz exp line me how to place the value to this place holders.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).list();
ses.close();
Thanks in advance
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo rp where rp.email = :emailAddress and rp.pwd = :password";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("emailAddress", Your email address)
.setParameter("password", Your password)
.list();
ses.close();
You should use a prepared statement instead of a string. example here
PreparedStatement preparedStatement = con.prepareStatement ("from RegisterPojo where email=? and pwd=?");
preparedStatement.setString(1, "email");
preparedStatement.setString(2, "password");
You have to modify your query like this,
query = "from RegisterPojo where email =:email and pwd =:password ";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("email",emailVal)
.setParameter("password",emailVal)
.list();
Read the hql docs here
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
ses.close();
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo where email = '" + varEmailAddress + "' and pwd = '" + varPassword + "'";
List<RegisterPojo> list = ses.createQuery(query).list();
ses.close();
Sorry This Is not Answer but instead another case, in above case #Grigoriev Nick suggested
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
but here the script starts with directly from clause while what if I want want to used sql like below
WITH A (
/// do some selection from many tables using various union as per my requirement
),
B (
/// another set of sqls for different set of data
)
select XXX from A a join B b on a.XYZ = b.xyz
where
/// few more fixed where clause conditions
AND A.SOME_COLUMN = ? // Here Instead Of String Concatenation I want to
//use Query parameters but using hibernate instead of raw Prepares statements
I am running an aggregate function in java through hibernate and for some reason it is giving me this error:
INFO Binary:182 - could not read column value from result set: l_date; Column 'l_date' not found.
When I run the MySQL query the column names are l_date and logins and I can not figure out why it is not finding that.
I have tested the query in MySQL and verified that it does work. My function looks as follows.
public List<Logins> getUserLoginsByMonth() {
Session session = getSessionFactory().openSession();
ArrayList<Logins> loginList = null;
try {
String SQL_QUERY = "SELECT l_date as l_month, SUM(logins) as logins FROM (SELECT DATE_FORMAT(login_time, '%M') as l_date, COUNT(DISTINCT users) as logins FROM user_logins WHERE login_time > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY DATE(login_time)) AS Z GROUP BY(l_month)";
Query query = session.createSQLQuery(SQL_QUERY);
List results = query.list();
for(ListIterator iter = results.listIterator(); iter.hasNext() ) {
Objects[] row = (Object[])iter.next();
System.out.println((Date)row[0}]);
System.out.println((BigInteger)row[1]);
}
}
catch(HibernateException e) {
throw new PersistenceDaoException(e);
}
finally {
session.close();
}
}
You need to add aliases as:
query.addScalar("l_month");
query.addScalar("logins");
and then call query.list();
It should work fine. addScalar is part of SqlQuery.