how to write query in hibernate - java

I have one table, User, and in that table, I have 3 columns:
id
name
email
I want to retrieve a name for a particular email by passing the email id; how would I write that hibernate query?

Using a criteria query:
Criteria criteria = getSession().createCriteria(User.class);
criteria = criteria.add(Restrictions.eq("email", email));
List<User> results = (List<User>) criteria.list();
Using hql:
String hql = "from User where email = :email";
Query query = getSession().createQuery(hql);
query.setParameter("email", email);
List<User> results = (List<User>) query.list();

Related

Hibernate: Criteria & createSQLQuery: how to get proper JSON?

When I try this I get the proper JSON as a result, but it takes a lot of time:
Criteria c = sessionFactory.getCurrentSession().createCriteria(User.class);
List<User> users = c.list();
List<User> specialUsers = new ArrayList<>();
for (User user : users) {
List<Perm> userPerms = user.getProfile().getPerms();
for (Perm perm : userPerms) {
if (perm.getId().equals(SPECIAL_ID)) {
specialUsers.add(user);
}
}
}
return specialUsers;
and the JSON is like:
[{"id":111,"name":"Name111"},{"id":222,"name":"Name222"}]
In attempt to improve performance I tried code below. In SQL app the results are OK, a few records of users:
String sql = "SELECT u.id, u.name FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
List<User> specialUsers= (List<User>)sessionFactory.getCurrentSession()
.createSQLQuery(sql)
.setParameter("rightId", SPECIAL_ID)
.list();
return specialUsers;
Now the 'JSON' however looks like this:
[[111,"Name111"],[222,"Name222"]]
I tried several things, like select *, criteria.add(Restrictions...) but to no effect. What I noticed is that in the first case specialUsers.toString returns proper data, in the second case it returns meaningless Strings like Ljava.lang.Object;#23e1469f.
Any hints how to solve this?
I managed to solve this in this way, may not be perfect:
// get ids of all special users
String sql = "SELECT u.id FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
List<Integer> intIds = sessionFactory.getCurrentSession()
.createSQLQuery(sql)
.setParameter("rightId", SPECIAL_ID)
.list();
// convert to long values
List<Long> longIds = intIds.stream()
.mapToLong(Integer::longValue)
.boxed().collect(Collectors.toList());
// get all special users
Criteria c = sessionFactory
.getCurrentSession()
.createCriteria(User.class)
.add(Restrictions.in("id", longIds));
List<User> specialUsers = c.list();
return specialUsers;
}

How to write the JPQL equavalent of db.Person.find({_id:{pid:'1',email:'test#gamil.com'}})

How to convert the mongo db query into JPQL query
I have tried the followings but its returning empty list.
Query query = manager.createQuery("SELECT p FROM Person p WHERE p.pid =:pid AND p.email =:email");
query.setParameter("pid", 1);
query.setParameter("email", "test#gmail.com");
List recs = query.getResultList();

Hibernate many-to-many retrieve list with condition

Im working with hibernate and java. I have an Group class and a User class. They share a many-to-many relationship as shown in this ERD .
What Im trying to achieve is that I want to retrieve a list of groups with the condition that they contain a User with a certain User_id.
In the GroupDao I have defined a function retrieveForUser in which I tried to retrieve the list using hibernate query language:
public List<Group> retrieveForUser(int userid){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("id", userid);
List<Group> list = query.list();
session.getTransaction().commit();
return list;
}
When I try to loop throught the resulting list using:
for(Group g : groupDao.retrieveForUser(user1.getId())){
System.out.println(g.getName());
}
I get the following errormessage:
java.lang.ClassCastException: java.util.HashMap cannot be cast to nl.hu.jelo.domain.group.Group
Question
How can I achieve it so that I end up with an List<Group> with only groups that contain a User with an certain User_id
You do not need to set result transformer. ALIAS_TO_ENTITY_MAP is for other purpose.
Simply do
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", userid);
is good enough.
Something off topic, are you sure you want to handle transaction manually like that?

hibernate query not working in java spring

I have this code and its working fine
Registration person = (Registration) session.get(Registration.class, 8);
person.setConfirmed(true);
session.save(person);
but this is not working , says mapping error
String query = "FROM registration WHERE user_id = 8";
Query query2 = session.createQuery(query);
Registration person = (Registration) query2.uniqueResult();
person.setConfirmed(true);
session.save(person);
This is my registration class
#Column(name = "user_id")
public Integer getUserId() {
return userId;
}
Because you are using a non-native query language, you probably need something like
String query = "FROM Registration WHERE userId = 8";
#Pasha, the following code is a SQL query not a HQL query.
String query = "FROM registration WHERE user_id = 8";
Query query2 = session.createQuery(query);
If you must run a SQL query, use the following instead:
String query = "FROM registration WHERE user_id = 8";
Query query2 = session.createSQLQuery(query);
query2.executeUpdate();
To convert the SQL query to a HQL query, assuming the Registration class has userId field:
String query = "FROM registration WHERE userId = 8";
Query query2 = session.createQuery(query);
query2.executeUpdate();
For a complete example, see the following guide: http://krams915.blogspot.com/2011/03/spring-hibernate-one-to-many.html

HIbernate query

I want to execute a query using hibernate where the requirment is like
select * from user where regionname=''
that is select all the users from user where region name is some data
How to write this in hibernate
The below code is giving result appropraitely
Criteria crit= HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName));
Well as you alaready said you can either use the Criteria API or create a HQL query:
// Criteria
List<User> users = HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName)).list();
// HQL
String query = "SELECT FROM User WHERE regionName = :region";
List<User> users = HibernateUtil.getSession().createQuery(query).setString("region", regionName).list();
String hql = "SELECT u FROM User u WHERE regionName=:regionName";
Query q = session.createQuery(hql);
q.setParameter("regionName", regionName);
List result = q.list();

Categories

Resources