Identifying the particular CRUD operation from the session object in hibernate - java

I am relatively new to hibernate. I am developing a java application which uses hibernate to do the basic CRUD operations. I wanted to add some logic specifically when I am doing a read from database. For all the operations, I do a session.createQuery to generate the query and do the operation. Is there some flag available in session object or any other related objects which differentiates a read/find operation from the rest of the CRUD operations. I wanted to add the logic where I create the HQL query from the session object.
Thanks in advance for any help in this regard.

you can use criteria, for example to find all objects related to the class USER:
public List<USER> findAllOBJECTS() {
Criteria criteria = createEntityCriteria().addOrder(Order.asc("nom"));;
return (List<USER>) criteria.list();
}
or if you want to search for a user by his login for example:
public USER findByLOGIN(String login) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("login", login));
USER user = (USER)crit.uniqueResult();
return user;
}

Related

How to do hibernate pagination in spring bean?

I have spring dao bean called HostelDaoImpl. It uses hibernate criteria api to retrieve results.
public class HostelDaoImpl extends AbstractGenericDao<Hostel, Integer> implements HostelDao {
public HostelDaoImpl() {
super(Hostel.class);
}
public List<Hostel> findHostelBy(HostelSearch hs) {
Criteria criteria = currenSession().createCriteria(Hostel.class);
criteria.setReadOnly(true);
Calendar beginDate = hs.getBeginDate();
String country = hs.getCountry();
if (beginDate != null)
criteria.add(Restrictions.le("beginDate", beginDate));
if (country != null) {
criteria.add(Restrictions.eq("country", country));
}
criteria.setProjection(Projections.rowCount());
Integer foundHostelsCount = (Integer) criteria.uniqueResult();
if (foundHostelsCount > 100) {
// do pagination
}
}
}
Now in place of those comments I need pagination.
I want to create Criteria only once and then store Criteria somewhere and call Criteria's setFirstResult and setMaxResults each time when user requests new portion of data.
Where to store Criteria if spring bean HostelDaoImpl is singleton and if I create instance variable Criteria criteria it is concurrently unsafe.
Where to store Criteria so that it is thread safe?
But if you know better way to achieve hibernate pagination in spring bean please provide it.
Thanks!
You can use CRUD repositories. It supports pagination
http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html
I'm using the Jquery plugin JQGrid to show in a table the results, and it's very easyly to hibernate pagination.
http://jqgrid.com/
You can use pageRequest for pagination.
follow the steps on this link.
This link is very helpful. The link explains everything till JSP page.

Search for a field in an entity passing an array of fields

Im trying to perform a search using Hibernate Criterias to be able to search for a field in a entity passing an array of values. For example : you have a entity USER that has a CAR or a list of CARĀ“s. Then I want to perform a search where I can chose several different cars and retrieve all users that have one of the cars that I listed...
Does anyone know how to do that using Hibernate Criteria?
Using JSF, Hibernate, MySQL
Thanks for you time.
#SuppressWarnings("unchecked")
public List<String> userList(String car){
Query query = em.createQuery("SELECT table.user FROM table WHERE table.car = :car");
query.setParameter("car", car);
List<String> queryResults = query.getResultList();
return queryResults;
}
This query will return all users that own the specified car.

OneToMany association with JoinTable returning null

In short: A user has many "not clients" (these are the clients the user cannot serve). User is associated to multiple clients through a join table.
User class: https://gist.github.com/dd99690fcaaba2c834d6
Client class: https://gist.github.com/10de71bcd1914ded5fb9
DAO: https://gist.github.com/dd4a369d60a05460d0c0
the "notClients" attribute in User is always null, can anyone help me understand why?
In short, because you're not including it in your select query. Not sure why you're writing out SQL queries and using the bean transformer? That's a very strange way to use hibernate. In the end it means what you're getting back is not a hibernate managed entity. It's just an object with the specific stuff that you selected mapped onto it.
The "normal"/"correct" way to use hibernate would be something like this:
private User getUser(int id, String userType)
{
User result;
session = HibernateUtil.getWilsonsSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select u from User u
where u.id = :id and u.role = :role");
query.setParameter("id", id);
query.setParameter("role", userType);
result = (User)query.uniqueResult();
session.getTransaction().commit();
return result;
}
Then what you get back is an Hibernate entity that will have all its mapped properties populated.
(would not personally use uniqueResult in that way either, but I am willing to admit that is largely a style preference.)

CouchDB Ektorp Select Query

I am examining example Blog example of CouchDB. I use Ektorp at Spring for CouchDB. I wanted to implement it into my application. I have users at my couch db when I use that:
#GenerateView
#Override
public List<User> getAll() {
ViewQuery q = createQuery("all")
.descending(true)
.includeDocs(true);
return db.queryView(q, User.class);
}
However it returns just last record. Any ideas to get all users?
It works well problem was about db names that's written at Spring configuration file.

Java query db issues. using hibernate and struts2

I am getting into java here. Fun and frustrating all at the same time :)
I have a simple method called showUsernames():
public String showUsernames(){
TimesheetUserDAO su = new TimesheetUserDAO();
Session session = su.getSession();
setUsers(su.findByUsername(_users));
session.close();
return SUCCESS;
}
...however, I am having a time getting just the usernames out of the database. It is possible with the Hibernate DAO to get this correct? I am able to use su.findAll() and return everything.
Any thoughts? Need more code? Thanks :)
The DAO probably executee a request like
select u from User u where ...
Change the query to
select u.name from User u where ...
Of course, instead of having a List<User> as a result, you'll have a List<String>.
This is basic stuff described in the Hibernate reference documentation. Have you read it?
Also, getting the session from the DAO and closing it manually like this shows a design problem. This should be encapsulated by the service layer or, even better, by the declarative transaction handling.

Categories

Resources