how to retrieve records in JPA - java

I am having a record with some values in db(MySQL) + eclipselink. I am using following code to retrieve that record
EntityManager em = DBUtil.getEntityManager();
TypedQuery<User> query = em.createQuery("select u from User u where u.email='tomj#abc.com'", User.class);
List<User> results = query.getResultList();
for(User u:results){
System.out.println(u.getEmail());
}
the record in my sample db has a row with email 'tomj#abc.com'. Still when I print the list I get blank / empty list printed. I think I am going wrong somewhere. Can anyone tell me what is the mistake?
PS: I also tried to use getSingleResult which throws an exception.

Related

Hibernate get List from database

In the following code I am trying to get a List of Products which contains all the products in the database:
public List<Products> getAllProducts() throws Exception{
try{
List<Products> products ;
org.hibernate.Transaction tx = session.beginTransaction();
products = session.createSQLQuery("SELECT * FROM Products").list();
if(products.size() > 0)
{
return products;
}
return null;
}
catch(Exception e)
{
throw e;
}
}
however this exception is thrown:
[Ljava.lang.Object; cannot be cast to mediatek.Products
List<Products> list = session.createCriteria(Products.class).list();
This will give you all the records of products table from database
Your answer not only adds a cast, but switches from SQL to HQL. Since your 2nd query is in HQL, Hibernate is able to use mapping information to know what class to return. This is the preferred way to do things in Hibernate, but if you had to use SQL for some reason you could achieve the same thing with:
(List<Products>)session.createSQLQuery("SELECT * FROM Products").addEntity(Products.class).list();
In Hibernate 5 the session.createCriteria methods are deprecated.
You will need to use a CriteriaBuilder and query from there to get a generic list of Products instead of just List.
Imports
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
Code
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Products> criteria = builder.createQuery(Products.class);
criteria.from(Products.class);
List<Products> products = session.createQuery(criteria).getResultList();
Forgot to type cast the query. it is working now.
List<Products> products = (List<Products>) session.createQuery("from Products").list();
For example you have code:
Session session = getSessionFactory().openSession();
Transaction transaction = null;
try {
SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM schema.yourtable WHERE param = :param");
sqlQuery.setString("param", "someParam");
And if your next step will be:
List list = sqlQuery.list();
You will receive list with Rows. You can see your Entity.class parameters in debug, but cat cast to List with your Entities:
List<Entity> list = (List<Entity>) sqlQuery.list();
In this point will be ClassCastException!
And if you need received List with your Entities you must add entity type to sql query:
List<Entity> list = (List<Entity>)sqlQuery.addEntity(Entity.class).list();
That's all. I hope someone will help.
if you using sql query, you should add this line at the last of the query to get the list you want:
.setResultTransformer(Transformers.aliasToBean(testDTO.class)).list();

Hibernate Iterator retrieving same data

I have a form that is connected to the database via hibernate. With this form, the user can go in and fill out fields such as names, address, and email information, etc. After they are all done filling out information they would submit the form. After submit, all the information would be display on a data table on the same page.
I am using session to interact with the database. However, the data that is being populated from database doesn't seem to be right.
public void somefunction() {
//The sessionfactory is being configured in another class
Session s = sessionFactory.openSession();
Transaction tx= null;
try {
tx= s.beginTransaction();
List userInformation = s.createQuery("FROM database1 WHERE PKEY ='"+somevalue+"'").list();
for(Iterator iterator = userInformation.iterator; iterator.hasNext();){
//database1 is an entity bean
database1 x = (database1) iterator.next();
System.out.print(x.getName());
}
tx.commit();
}
catch(Exception) {......}
finally {.....}
}
After the user submit the first "user" with their information, everything shows up in the datatable fine. However, when they enter a second "user" the row displayed on the datatable is the same information as the first user, even though the data is different. I think the code looks correct, so i am not sure what could be wrong with this.
you should use primary key to get correct value.
List userInformation = s.createQuery("FROM database1 where yourId='PK'").list();
In your query always it will return first row.
Found the solution.
Instead of using session.createQuery("QUERY"), I used
Criteria cr = session.createCriteria(SomeClass.class)
cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
cr.add(/* add some filters here */);
ScrollableResults sr = cr.scroll(ScrollMode.FORWARD_ONLY);
while(sr.next) {
someObject so = (someObject) sr.get(0);
//Do action here
}
that solved my problem of returing a single result.

hibernate results join left

I've stack over one small thing:
I have two tables in database, which are related - User and UserReference.
In UserReference i have field userid, which is related to id in User.
i have query to mysql with join left:
"FROM User as user left join fetch user.userReferences WHERE login='"+login+"' or email='"+login+"' AND password = '" +password+ "'" ;
The query is ok and i get results.
I send the results to controller, changing it into list: query.list();
In controller i receive the results and push it into user list.
From the user list i can get info from table User
In table User there is:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserReference> getUserReferences() {
return this.userReferences;
}
And now - i want to get data from table UserReference which are in user list, becouse my query have JOIN.
How can i do it?
i was trying to do something like this:
List<UserReference> userReference = (List<UserReference>) user.get(0).getUserReferences();
System.out.println(userReference.get(0).getAge());
But it doesn't work.
Can you help me ?
You can't cast a Set to a List, iterate over the Set to get userRefences instead.

DAO method retrieve single entry

How can I write DAO method which will return as a result only first entry from the database. For instance lets say I'm looking at Users table and I want to retrieve only the first entry, I'd declare method like:
public User getFirstUser(){
//method logic
}
EDIT:
User has primary key id if that matters at all.
I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. thank you
My attempt :
public User getFirstUser(){
try {
final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)";
final Query query = getSession().createQuery(getQuery);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("get successful");
// return what??
} catch (RuntimeException re) {
log.error("get not successful", re);
throw re;
}
}
You can
use:
Query query = session.createQuery("from User");
query.setMaxResults(1);
User result = (User) query.uniqueResult();
use User user = session.get(User.class, id); if you know the ID upfront.
Get all users ordered by id and limit the results to 1 (but don't use LIMIT, use setMaxResults() to remain portable):
Query q = session.createQuery("from User u order by u.id");
q.setMaxResults(1);
User u = (User) q.uniqueResult();
SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)
:)
Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so...
But this method perhaps throw exception when multiple results are returned... can't remember...
Actually there is also getResultList returning a List of entities, and you could do list.get(0) no?
Or create a query with LIMIT 1?
In MS SQL Server we do it like,
First user, min ID,
SELECT TOP 1 * FROM Users ORDER BY Id
Latest user, max ID,
SELECT TOP 1 * FROM Users ORDER BY Id DESC
thanks.

working with object with spring and hibernate

hope everybody is cool.I've been trying to do something with spring-hibernate but it's still a failure.i'm very new to it.i need a little help.supposing a POJO class Users.i want to return an Users object by username.While i had no problem to return Users object by id by doing this
return (Users) getHibernateTemplate().get(Users.class, id);
it seems to be a challenge for me getting the Users object by username. I've tried this
List<Users> users = getHibernateTemplate().find("from Users u where u.username=?",username);
return users.get(0);
and even this
return (Users)getHibernateTemplate().find("from Users u where u.username=?",username).get(0);
how should i do it.And what is the proper way to return an array of Users objects and/or List.Thanks for reading this.
Try this
Query q = session.createQuery("select * from Users u where u.username=:username");
q.setString("username", username);
maybe you can try this?
List l =getHibernateTemplate().find("from Users u where u.username=?",new Object[]{username});
if (l.size() > 0)
return (User)l.get(0);
else
return null;
Another better way is to use Criteria. See the example below.
DetachedCriteria deCriteria = DetachedCriteria.forClass(User.class, "u");
Criteria criteria = deCriteria.getExecutableCriteria(session);
criteria.add(Restrictions.eq("u.username", username));
List<User> userList = criteria.list();

Categories