session工具类——获取session:
package com.imooc.ssh.Util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.annotation.Resource;
public class BaseSessionFactoryImpl {
@Resource
private SessionFactory sessionFactory = null;
public Session getSession(){
return sessionFactory.getCurrentSession();
}
}
session使用:
@Repository
public class PersonDao extends BaseSessionFactoryImpl {
// @Resource
// private SessionFactory sessionFactory;
public List<Person> getPerson(){
CriteriaQuery<Person> criteriaQuery = getSession().getCriteriaBuilder().createQuery(Person.class);
criteriaQuery.from(Person.class);
return (List<Person>) this.getSession().createQuery(criteriaQuery).getResultList();
}
public Person getPersonById(String id){
return (Person) this.getSession().createQuery("from Person where id = ?0").setParameter(0, id).uniqueResult();
}
public void addPerson(Person person){
this.getSession().save(person);
}
public void updatePerson(Person person){
this.getSession().update(person);
}
public void deletePersonById(String id){
this.getSession().createQuery("delete Person where id = ?0 ").setParameter(0,id).executeUpdate();
}
}