hibernate之session使用

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


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章