Code:
public void getDetails() {
try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.list();
session.getTransaction().commit();
for (CrbtSubMasterDemo pojo : itr) {//excepion line
System.out.println("[" + pojo.getMobile() + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}
CrbtSubMasterDemo is pojo mapped with the db.
When I try to run it, it gives following Exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.telemune.demoPojo.CrbtSubMasterDemo
at com.telemune.demoHibernate.QueryTester.getDetails(QueryTester.java:57)
at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:23)
The question is query.list() is returning the list of objects of pojo class. Then why is this Exception. I am new to Hibernate, sorry if its a silly question.
When you write this:
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Your result set is not a List of CrbtSubMasterDemo
Try to write:
String hql = "select FROM CrbtSubMasterDemo c where rownum<20";
Another way is define a new constructor of CrbtSubMasterDemo where you pass only two fields c.mobile, c.password
so your query becomes:
String hql = "select new " + CrbtSubMasterDemo.class.getName() + "(c.mobile, c.password) FROM CrbtSubMasterDemo c where rownum<20";
If you follow this solution, remeber to add a default constructor too (without parameters), so in your pojo you have:
public CrbtSubMasterDemo(String mobile, String password) {
this.mobile = mobile;
this.password = password
}
and
public CrbtSubMasterDemo() {
}
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
Result of this will be List<Object[]>
List<Object[]> itr = query.list();
for (Object[] row : itr) {
System.out.println(String.format("mobile:%s, password:%s", row[0], row[1]));
}
if mobile and password are strings, of course. You can use a transformer to transform results directly to CrbtSubMasterDemo.
Hibernate 3.2: Transformers for HQL and SQL
FluentHibernateResultTransformer
Sir, Many times user faces this kinda requirements . Hibernate has ResultTransformer to convert a hql/sql in Object.
public CrbtSubMasterDemo{
private Stirng mobile;
private String password;
public CrbtSubMasterDemo(){
--------------
}
#####after setting the transation set whichever columns you are selecting should be given as name of property of your object
String hql = "select c.mobile as mobile, c.password as password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.setResultTransformer(Transformers.aliasToBean(CrbtSubMasterDemo.class) ).list();
##No need to commit the transaction.
}
It will convert you query into the CrbtSubMasterDemo
Do not directly cast the result of "query.list();" to List of CrbtSubMasterDemo. As query.list() return object list. Iterate over the object list received and cast one by one to put in list List of CrbtSubMasterDemo
Related
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
}
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
query.setString("school","");
query.setString("isActive", "Y");//working
query.setString("isActive", "N");//working
query.setString("isActive", "Y","N"); // not working
query.setString("isActive", "'Y','N'"); // not working
return query.list();
I have no idea if the code below should work, I was wondering if i can pass list of values to my search string parameter so there's no need for me to create to queries ; one for select all data regardless of status and another to select only active data.
Use Query.setParameterList() to pass in a List as a parameter:
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
List<String> isActiveList = new ArrayList<>();
isActiveList.add("Y");
isActiveList.add("N");
query.setParameterList("isActive", isActiveList);
return query.list();
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);
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();
}}
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();