一、增删改查
首先把SessionFactory封装成一个工具类,避免代码重复性:SessionFactoryUtil
package com.gw.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory(){
Configuration configuration= new Configuration().configure();//实例化
ServiceRegistry serviceRegistry =new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();//实例化服务登记
return configuration.buildSessionFactory(serviceRegistry);//获取Session工厂
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
如此,我们就能在执行类中直接使用它:
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private void add(){
Session session = sessionFactory.openSession();//创建新的 Session
session.beginTransaction();// 开启事物
Student s = new Student();
s.setName("朴树");
session.save(s);
session.getTransaction().commit();// 提交事务
session.close();//关闭session
}
private void delete(){
Session session = sessionFactory.openSession();//创建新的 Session
session.beginTransaction();// 开启事物
Student student = (Student)session.get(Student.class,Long.valueOf(2));
session.delete(student);
session.getTransaction().commit();// 提交事务
session.close();//关闭session
}
注意:其中的Long.valueof(2) 表示主键为2的对象,下同
update:
private void update(){
Session session = sessionFactory.openSession();//创建新的 Session
session.beginTransaction();// 开启事物
Student student = (Student)session.get(Student.class,Long.valueOf(3));
student.setName("崔健");
session.save(student);
session.getTransaction().commit();// 提交事务
session.close();//关闭session
}
select:
private void getAllStudent(){
Session session = sessionFactory.openSession();//创建新的 Session
session.beginTransaction();// 开启事物
String hql="from Student";
Query query= session.createQuery(hql);
List<Student> lstStudent = (List<Student>)query.list();
for(Student s :lstStudent){
System.out.println(s);
}
session.getTransaction().commit();// 提交事务
session.close();//关闭session
}
其中 "from Student" 后面可以加条件语句 比如where id= 3 达到和sql一致的效果。
二、注解模式
注解模式不需要配置hbm.xml 直接在model类中加上相应的注解即可达到相同的效果
首先在类名上放加上
//Entity代表映射实体
@Entity
@Table(name="t_teacher")
public class Teacher {
table表示生成和访问的表名
然后在主键相应的get方法上方 加上:
@Id //主键
@GeneratedValue(generator="_native") //生成策略
@GenericGenerator(name="_native",strategy="native")
public long getId() {
return id;
}
native表示该字段自增
如此,即可达到和 (一) 相同的效果。
三、junit4
使用junit4测试框架 ,我们需要在项目中引入 junit4 jar包
然后选取相应要测试的类,(注意:该类如果要用junit4测试,则该类下的方法需要是public)
鼠标右击该类——>New——>Junit test case 再进行相关参数配置后,就可以生成相应的测试类
然后展开该测试类文件——>右击方法名——>Run As——>junit test 即可执行测试。