上一篇文章
https://www.nasuiyile.cn/70.html
上一篇文章实现了hibernate的配置
现在来看看hibernate的基本使用吧,将上篇文章的一些常用方法封装了工具类
HibernateUtil
package com.myxq.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static{
//加载配置文件,如果不传参的话默认是传这个参数
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
//创建seessionFactory jdbc连接池
//创建session,session并不是轻量级的,一般情况下,一个项目用一个sessionFactory就够了
// ,需要操作多个数据库,可以为每个数据库指定一个SessionFactory
//内部维护了Hibernate的连接池和二级缓存
sessionFactory =configure.buildSessionFactory();
}
public static Session openSession(){
Session session=sessionFactory.openSession();
return session;
}
}
接下来是增删改查(curd的实现方法)
package com.myxq.test;
import com.myxq.domain.Customer;
import com.myxq.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.junit.Test;
import java.util.List;
public class HibernateTest {
@Test
public void test1(){//增
Session session= HibernateUtil.openSession();
Customer customer=new Customer();
customer.setCust_name("myxq");
customer.setCust_level("2");
//保存,设置了id就是修改操作,没有设置id就是添加操作
session.save(customer);
//释放资源
session.close();
}
@Test
public void test2(){//查
Session session= HibernateUtil.openSession();
//查询id为1的数据
Customer customer = session.get(Customer.class, 1L);
System.out.println(customer);
session.close();
}
@Test
public void test3(){//改
Session session= HibernateUtil.openSession();
Transaction transaction=session.beginTransaction();
//查询id为1的数据
Customer customer = new Customer();
customer.setCust_id(1L);
customer.setCust_name("myxq_update2");
session.update(customer);
//提交事务
transaction.commit();
session.close();
}
@Test
public void test4(){//删
Session session= HibernateUtil.openSession();
Transaction transaction=session.beginTransaction();
//查询id为1的数据
Customer customer = new Customer();
customer.setCust_id(3L);
session.delete(customer);
//提交事务
transaction.commit();
session.close();
}
@Test
public void test6(){//查询全部的记录
Session session=HibernateUtil.openSession();
Transaction transaction=session.beginTransaction();
//查询所有的hql,后面的参数为类的全路径
Query query = session.createQuery("from com.myxq.domain.Customer");
List<Customer> list = query.list();
for (Customer customer:list) {
System.out.println(customer);
}
transaction.commit();
session.close();
}
}