package com.qm.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.qm.entity.Student; /** * 持久层 * @author quanmin * */ public class StudentDao { public static void main(String[] args) { testSave(); //testFind(); //testUpdate(); //testDelete(); //testFindList(); } /** * 查询所有 */ private static void testFindList(){ Configuration conf=new Configuration(); conf.configure("hibernate.cfg.xml"); //创建工厂 SessionFactory sf=conf.buildSessionFactory(); //取得session Session session=sf.openSession(); //sql是查询表名 hql是查询类名 String hql="from Student"; Query query=session.createQuery(hql); List<Student> studentList=query.list(); for (Student student : studentList) { System.out.println(student.getName()+"="+student.getPassword()+"="+student.getHight()+"="+student.getSex()); } session.close(); sf.close(); } /** * 删除 */ private static void testDelete(){ Configuration conf=new Configuration(); conf.configure("hibernate.cfg.xml"); //创建工厂 SessionFactory sf=conf.buildSessionFactory(); //取得session Session session=sf.openSession(); //开始事务 session.beginTransaction(); Student student=new Student(); student.setId(10); session.delete(student); session.getTransaction().commit(); session.close(); sf.close(); } /** * 更新 */ private static void testUpdate(){ Configuration conf=new Configuration(); conf.configure("hibernate.cfg.xml"); //创建工厂 SessionFactory sf=conf.buildSessionFactory(); //取得session Session session=sf.openSession(); //开始事务 session.beginTransaction(); //封装 Student student=(Student)session.load(Student.class,8); System.out.println(student.getName()+"="+student.getPassword()+"="+student.getHight()+"="+student.getSex()); student.setName("全哥哥"); session.update(student); System.out.println(student.getName()+"="+student.getPassword()+"="+student.getHight()+"="+student.getSex()); session.getTransaction().commit(); session.close(); sf.close(); } /** * 查找一个 */ private static void testFind(){ Configuration conf=new Configuration(); conf.configure("hibernate.cfg.xml"); //创建工厂 SessionFactory sf=conf.buildSessionFactory(); //取得session Session session=sf.openSession(); //封装 Student student=(Student)session.load(Student.class,8); System.out.println(student.getName()+"="+student.getPassword()+"="+student.getHight()+"="+student.getSex()); session.close(); sf.close(); } /** * 保存 */ private static void testSave() { Configuration conf=new Configuration(); conf.configure("hibernate.cfg.xml"); //创建工厂 SessionFactory sf=conf.buildSessionFactory(); //取得session Session session=sf.openSession(); //开始事务 session.beginTransaction(); Student student=new Student("quanmina","123",172,1); session.save(student); System.out.println("保存成功"); session.getTransaction().commit(); session.close(); sf.close(); } }