This is the method I'm using:
public int getId(String proyectName)
{
int idproyect=0;
try
{
Session session= hibernateUtil.getSessionFactory().openSession();
String hql = "Select idproyect from proyect where name= :proyectName";
Query query = session
.createQuery(hql);
query.setParameter("proyectName", proyectName);
idproyect= (Integer)query.uniqueResult();
}
catch(Exception e)
{
}
return idproyect;
}
No matter the variable is being inyected into the method the result I'm getting is 0 which matches with the idproyect default value.
I checked my logs and the select is being executed but the result is still 0, no matter what.
I think It has to do with the query conversion into Integer unique value.
This problem has concerned me for like 2 days but I ignored until today because I need to solve it to carry on with my project.
I don't think its relevant but I'm using Hibernate to persist the classes.
you try this to get single int value
String hql = "Select idproyect from proyect where name= :proyectName";
Query query2 = entitymanager.createNativeQuery(hql).setParameter("proyectName", proyectName);
BigInteger obj = (BigInteger) query2.getSingleResult();
System.out.println("%%%%%%%" + obj);
System.out.println(obj);
long id = Long.valueOf(obj.toString()));
System.out.println(id);
Related
I'm trying to fetch a single boolean field from a huge entity. If has_Id in mysql db is 0, the JPA query below (simplified extract) works fine and returns the correct Boolean 'false' value. Exactly the same query does not return any result if has_Id == 1.
I'm using Mysql 5.7, eclipselink as JPA implementation.
The field in question is of boolean type:
TINYINT(1) NOT NULL DEFAULT '0'
-tried with different type of Query constuctors (we use EclipseLink)
-used Long & Integer type, instead of Boolean
-the same query and parameters works fine in mysql itself.
try {
TypedQuery<Boolean> query = buildQuery(Boolean.class,
"select x.hasId from CCC x" + STD_VARS, null, new EqualFilter("tenantId", tenantId));
return query.getSingleResult();}
catch (NoResultException e) {
return null;
}
Below is the body of buildQuery:
protected <R> TypedQuery<R> buildQuery(Class<R> type, String select, SortInfo sortInfo, String orderTemplate, JqlFilter... filters) {
String stm = buildStatement(select, sortInfo, orderTemplate, filters);
EntityManager em = emProvider.get();
TypedQuery<R> query = em.createQuery(stm, type);
return query;
}
STD_VARS are templates for where and order clauses, EqualFilter is used to fill them.
In Simple JDBC (with no Hibernate)
we can do batch select by changing only place holder, like this
PreparedStatement stmt = conn.prepareStatement(
"select id, name from users where id = ?");
for ( int i=0; i < 10; i++ ) {
stmt.setInt(i); // or whatever values you are trying to query by
// execute statement and get result
}
How we can do it in Hibernate?
Hope this helps you out,
String hql = "from Users s where s.id= :userId";
for(int i=0; i< 10;i++){
List result = session.createQuery(hql)
.setParameter("userId", i)
.list();
}
This is the most common and user friendly way. It use colon followed by a parameter name (:example) to define a named parameter
Example 1: Using setParameter() method
String hql = "from Student s where s.registerNumner = :registerNumner";
List result = session.createQuery(hql).setParameter("registerNumner", "12345").list();
The setParameter() method is smart enough to discover the parameter data type of bind variable.
Example 2: Using setString() method
You can use setString to tell Hibernate this parameter date type is String.
String hql = "from Student s where s.registerNumber = :registerNumber";
List result = session.createQuery(hql).setString("registerNumber", "12345").list();
Example 3: Using setProperties() method
This feature is great ! You can pass an object into the parameter binding. Hibernate will automatic check the object’s properties and match with the colon parameter.
Student student = new Student();
Student.setRegisterNumber("12345");
String hql = "from Strudent s where s.registerNumber = :registerNumber";
List result = session.createQuery(hql).setProperties(student).list();
Example 4:
You can use positional parameters also.
String hql = "from Student s where s.registerNumber = ? and s.studentName = ?";
List result = session.createQuery(hql).setString(0, "12345").setParameter(1, "Harshad").list();
But it’s vulnerable to easy breakage because every change of the position(i.e. index) of the bind parameters requires a change to the parameter binding code
Batch select:
You can use following way for batch select
String hql = "from Users s where s.id= :userId";
List finalResult = new ArrayList();
for(int i=0; i< 10;i++){
List result = session.createQuery(hql).setParameter("userId", i).list();
finalResult.addCollection(result );
}
i am new to this and today i tried to play hibernate with a method that returns the result of selected row...if is selected then it can return the result in int.. here is my method
public int validateSub(String slave, String source, String table){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery("from Subscribers where slave = :slave AND source = :source AND tbl = :tbl");
q.setParameter("slave", slave);
q.setParameter("source", source);
q.setParameter("tbl", table);
int result = q.executeUpdate();
return result;
}
from this method i tried to validate the 3 values that i get from the Subscribers table but at the end i tried to compile having this error
Exception in thread "Thread-0" org.hibernate.hql.QueryExecutionRequestException: Not supported for select queries [from com.datadistributor.main.Subscribers where slave = :slave AND source = :source AND tbl = :tbl]
You can have a look at the below links that how executeUpdate works, one is from the hibernate docs and other the java docs for JPA which defines when the exception is thrown by the method
http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate()
https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#executeUpdate()
Alternatively you can use
List list = query.list();
int count = list != null ? list.size() : 0;
return count;
you are running a select query, Eventhough you are not using the select keyword here hibernate will add that as part of the generated SQL.
what you need to do to avoid the exception is the say
q.list();
now, this will return a List (here is the documentation).
if you are trying to get the size of the elements you can say
Query q = session.createQuery("select count(s) from Subscribers s where slave = :slave AND source = :source AND tbl = :tbl");
Long countOfRecords = (Long)q.list().get(0);
you can execute update statements as well in HQL, it follows a similar structure as SQL (except with object and properties).
Hope this helps.
here you want to select record so it is posible without select key word
sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");
long size = list.get(0);
I also happened to make the same mistake today.
Your SQL statement is not correct.
You can try:
DELETE from Subscribers WHERE slave = :slave AND source
Try this:
int result = q.list().size();
I am new to hibernate . I want to pass 2 column values and want hibernate to return primary key of that table.
String queryString = "select perId from Permission where document.docId=1 and user.id=2";
return getHibernateTemplate().find(queryString);
But this method return List.
How can i return int value.
Use the uniqueResult() method in Query. see here for an example or read the api here.
Here is an example. Replace the place holders as need to use them.
sessionFactory = getHibernateTemplate().getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Query query = session
.createQuery("select value from table where ...");
query.setParameters("param1", value1);
result = (Type) query.uniqueResult();
You could do something like:
String sql = "select count(*) from table where ...";
BigDecimal count = (BigDecimal) hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery query = session.createSQLQuery(sql);
return (BigDecimal) query.uniqueResult();
}});
return count;
Here is another way using addScalar:
Query query = session.createQuery("select value from table where param1 = :param1").addScalar("value", Type);
query.setParameters("param1", value1);
result = (Type) query.uniqueResult();
Example of String:
Query query = session.createQuery("select value from table where param1 = :param1").addScalar("value", StandardBasicTypes.STRING);
query.setParameters("param1", value1);
result = (String) query.uniqueResult();
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.