一、增刪改查
首先把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 即可執行測試。