简体   繁体   中英

How to use hibernate session handling

Can you give me an example code in java, how to use the hibernate session correctly? I want one controller class to handle all hibernate operations (fetch, update, delete).

  private void addPersonToEvent(Long personId, Long eventId) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    Person aPerson = (Person) session.load(Person.class, personId);
    Event anEvent = (Event) session.load(Event.class, eventId);
    aPerson.getEvents().add(anEvent);

    session.getTransaction().commit();
}

is this the correct way? how can i handle exceptions and the rollback correctly to avoid connection pool errors, may if connection was not closed correctly after an exception?

Thank you very much

I want one controller class to handle all hibernate operations (fetch, update, delete).

You should have an super class to handle all common operation(fetch, update, delete). The super class should be like:

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
   public void create(T entity) {
    getSession().save(entity);
   }

  public void edit(T entity) {
    getSession().merge(entity);
  }

  public void remove(T entity) {
    getSession().remove(entity);
  }

  public T find(Object id) {
    return getEntityManager().find(entityClass, id);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM