working with object with spring and hibernate - java

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

Related

Loading Two Unrelated Entities (nothing in comman) in One Query [Spring Data JPA]

How can two unrelated entities , nothing in common be loaded in one Query using spring data jpa?
Current Code :
User user = userRepo.findOne(userId);
Post post = postRepo.findOne(postId);
This creates two sql query is there any way to do it 1 Query.
Is there any way doing like this
Object[] userAndPost = someRepo.findUserAndPost(userId, postId);
Please note both user and post are unrelated and have no common column on which join can be done.
Sandeep
You could refer to this answer and this post for a better explanation.
I have very little experience, but I've tested this code and it works for your particular case.
In the repo file (I'm using Spring boot):
#Repository
public interface UserDao extends JpaRepository<User, Long> {
#Query("select u, p from User u, Post p where u.id =:userId and p.id =:postId")
List<Object[]> findUserAndPost(#Param("userId") Long userId, #Param("postId") Long postId);
}
And then, to test if that worked, you could try this code:
List<Object[]> results = userDao.findUserAndPost(userId, postId);
for (int i = 0; i < results.size(); i++) {
User user = (results.get(i)[0] instanceof User) ? (User) results.get(i)[0] : null;
Post post = (results.get(i)[1] instanceof Post) ? (Post) results.get(i)[1] : null;
// Do whatever with user and post...
}

how to retrieve records in JPA

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.

Hibernate retrieve results from database based on condition

I am a bit lost when it comes to retrieving results from the database.
My MemberModel consists of 4 fields: id, username, password and email. I have been able to successfully save it to database.
Now I need to retrieve an id of a member who's username equals "Test".
I tried something along the lines:
SQLQuery query = session.createSQLQuery("SELECT id FROM members WHERE username = :username");
query.setString("username", username);
List<MemberModel> returnedMembers = query.list();
MemberModel member = returnedMembers.get(0);
int id = member.getId();
However I get an error that member.getId() cannot be converted to int, since it is MemberModel... But the getter getId() returns int.
I am quite confused. The question is: what would be the easiest and fastes way to retrieve member id based on condition (value of username)?
You are using a native SQL query, but should use HQL query. That means you have to change the query to:
session.createQuery("SELECT m FROM MemberModel m WHERE m.username = :username")
I would change your code into something like this:
public MemberModel getMember(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + MemberModel.class.getName() + " where username = :username ");
query.setParameter("username", username);
return (MemberModel) query.uniqueResult();
}
Then you should be able to do:
MemberModel model = someInstance.getMember("someUsername");
int id = model.getId();
You can also use criteria and restrictions api.
Criteria criteria = session.createCriteria(MemberModel.class);
criteria.add(Restrictions.eq("username", username));
MemberModel member=(MemberModel)criteria.uniqueResult();

JPA / Hibernate: CriteriaBuilder - How to create query using relationship object?

I have the following four tables:
SCHEDULE_REQUEST TABLE:
ID,
APPLICATION_ID (FK)
APPLICATION TABLE:
ID,
CODE
USER_APPLICATION TABLE:
APPLICATION_ID (FK),
USER_ID (FK)
USER TABLE:
ID,
NAME
Now I wanted to create a CriteriaBuilder where condition is to select ScheduleRequests for specified user Ids.
I have the following codes:
List<User> usersList = getSelectedUsers(); // userList contains users I wanted to select
CriteriaBuilder builder = getJpaTemplate().getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery<ScheduleRequest> criteria = builder.createQuery(ScheduleRequest.class);
Root<ScheduleRequest> scheduleRequest = criteria.from(ScheduleRequest.class);
criteria = criteria.select(scheduleRequest);
ParameterExpression<User> usersIdsParam = null;
if (usersList != null) {
usersIdsParam = builder.parameter(User.class);
params.add(builder.equal(scheduleRequest.get("application.userApplications.user"), usersIdsParam));
}
criteria = criteria.where(params.toArray(new Predicate[0]));
TypedQuery<ScheduleRequest> query = getJpaTemplate().getEntityManagerFactory().createEntityManager().createQuery(criteria);
// Compile Time Error here:
// The method setParameter(Parameter<T>, T) in the type TypedQuery<ScheduleRequest> is not
// applicable for the arguments (ParameterExpression<User>, List<User>)
query.setParameter(usersIdsParam, usersList);
return query.getResultList();
Can you please help me how to pass query filter to a relationship object?
I think what I did in "application.userApplications.user" is wrong?
Please really need help.
Thank you in advance!
Using the canonical Metamodel and a couple of joins, it should work. Try if you get some hints from the following pseudo-code (not tested):
...
Predicate predicate = cb.disjunction();
if (usersList != null) {
ListJoin<ScheduleRequest, Application> applications = scheduleRequest.join(ScheduleRequest_.applications);
ListJoin<Application, UserApplication> userApplications = applications.join(Application_.userApplications);
Join<UserApplication, User> user = userApplications.join(UserApplication_.userId);
for (String userName : usersList) {
predicate = builder.or(predicate, builder.equal(user.get(User_.name), userName));
}
}
criteria.where(predicate);
...
In order to understand Criteria Queries, have a look at these tutorials:
http://www.ibm.com/developerworks/java/library/j-typesafejpa/
http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html
The second link should also guide you on how to use Metamodel classes, that should be built automatically by the compiler / IDE.

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.

Categories