views:

66

answers:

3

Allot of my use of hibernate, at least for that data that is presented on many parts of the web application, is for read-only purposes.

I want to add some parameters to my Dao methods so I can modify the way hibernate pulls the data and how it handles transactions etc.

By 'pulls the data' I altering the locking and not having session worry about monitoring changes to the entities since I want read-only, read-uncommited (and any other performance tweaks there are?).

Example usage: Data on the front page of my website is displayed to the users, it is read-only, so I want to avoid any session/entity tracking that hibernate usually does.

This is data that is read-only, will not be changed in this transaction, etc.

What would be the most performant way to pull the data?

(the code below is c#/nhibernate, I'm implementing this in java as I learn it)

public IList<Article> GetArticles()
{
    return Session.CreateCriteria(typeof(Article))
                  // some where cluase
}
A: 

This might be helpful as to why there is no session.setReadOnly method

http://opensource.atlassian.com/projects/hibernate/browse/HHH-2672

Alternatively have a look at stateless session http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-statelesssession but be informed that there is no first level cache or second level cache support for this (so this might actually turn out to be a bad thing for your requirement.

Calm Storm
Thanks, well I guess I could add the object to ehcache myself.
Blankman
A: 

Use select new clause.

As said by JPA specification

The resulting entity instances are in the new state.

Be aware The constructor name must be fully qualified.

So you can use

select new br.com.model.domain.User(u) from User u

You should provide a constructor like this one

public class User {

    private String name;

    // required no-arg constructor
    public User() {}

    public User(User u) {
        this.name = u.name;

         // And so on...
    }

}

Or use either Spring BeanUtils or Apache Commons BeanUtils instead as follows

public User(User u) {
    // Spring BeanUtils
    BeanUtils.copyProperties(u, this);

    // Apache Commons BeanUtils
    BeanUtils.copyProperties(this, u);
}
Arthur Ronald F D Garcia
A: 

You can create a read-only session in hibernate:

Session session = ... // Hibernate session
session.connection().setReadOnly(true);
session.setFlushMode(FlushMode.NEVER);
// Your query...
session.connection().setReadOnly(false);
session.close();

Alternatively, you could simply rollback your transaction and nothing will get flushed (and no dirty check will be done).

Manuel Darveau