Hibernate = Column not found - java

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.

Related

Get entity by email in hibernate

I am trying to get the user from his email , the email is unique in the database.
I write this code :
session.beginTransaction();
User user = (User) session.createQuery("select * from `user` where email = '"+email+"'");
session.getTransaction().commit();
Is this code right ? or there is some function in hibernate to get entity by column value ?
I see two problems with your current code. First, you appear to be running a native SQL query, not HQL (or JPQL). Second, your query is built using string concatenation, leaving it prone to attack by SQL injection
Consider the following code:
Query query = session.createQuery("from User u where u.email = :email ");
query.setParameter("email", email);
List list = query.list();
Without writting any SQL:
public static Person getPersonByEmail(String email) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Person> cr = cb.createQuery(Person.class);
Root<Person> root = cr.from(Person.class);
cr.select(root).where(cb.equal(root.get("email"), email)); //here you pass a class field, not a table column (in this example they are called the same)
Query<Person> query = session.createQuery(cr);
query.setMaxResults(1);
List<Person> result = query.getResultList();
session.close();
return result.get(0);
}
example of use:
public static void main(String[] args) {
Person person = getPersonByEmail("test#mail.com");
System.out.println(person.getEmail()); //test#mail.com
}

HQL: Two conditions in where clause returning empty result

I am trying to select from db using HQL with two conditions as below:
String hql = "from User u where u.login=? and u.password=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
System.out.println(query);
query.setString(0, u);
query.setString(1, p);
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) query.list();
System.out.println(listUser);
if (listUser != null && !listUser.isEmpty()) {
return true;
}
return false;
But I am getting empty result. I tried by giving only one condition , then it is giving proper result. (i.e. from User u where u.login=?). How to achieve this with two conditions?

PostgreSQL DAO.java method to get single int value

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

Is there any spring jpa equivalent to following query

Query :
#Query("Select p.name,t.points from Player p,Tournament t where t.id=?1 And p.id=t.player_id")
I have my player and tournament entity and their corresponding JPA repositories. But the problem is we can get only entities from our query, but i want to do above query, please help me with this i am new to it.
this is my sql query i want to add but where to add i am not getting:
Select p.name, t.points_rewarded from player p, participant t where t.tournament_id="1" and t.player_id=p.id;
This is how you can do it with JPQL for JPA:
String queryString = "select p.name, t.points from Tournament t," +
" Player p where t.player_id=p.id " +
"and t.id= :id_tournament";
Query query = this.entityManager.createQuery(queryString);
query.setParameter("id_tournament", 1);
List results = query.getResultList();
You can take a look at this JPA Query Structure (JPQL / Criteria) for further information about JPQL queries.
And this is ho you can do it using HQL for Hibernate, these are two ways of doing it:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= '1' And p.id=t.player_id";
Query query = session.createQuery(hql);
List results = query.list();
Or using query.setParameter() method like this:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= :tournament_id And p.id=t.player_id";
Query query = session.createQuery(hql);
query.setParameter("tournament_id",1);
List results = query.list();
You can take a look at this HQL Tutorial for further information about HQL queries.
Note:
In both cases you will get a list of Object's array List<Object[]> where element one array[0] is the p.name and the second one is t.points.
TypedQuery instead of normal Query in JPA
this is what i was looking for, thanks chsdk for help, i have to create pojos class, and in above link answer is working fine foe me,
Here is my code sample
String querystring = "SELECT new example.restDTO.ResultDTO(p.name,t.pointsRewarded) FROM Player p, Participant t where t.tournamentId=?1 AND t.playerId = p.id ORDER by t.pointsRewarded DESC";
EntityManager em = this.emf.createEntityManager();
try {
Query queryresults = em.createQuery(querystring).setParameter(1, tournamentId);
List<ResultDTO> result =queryresults.getResultList();
return new ResponseEntity<>(result, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} finally {
if (em != null) {
em.close();
}}

How to execute series of select query in Hibernate?

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

Categories