二、hibernate的常用API
hibernate的调用过程
public class demo01 { @Test public void test(){ // 1.加载hibernate核心配置文件 Configuration configure = new Configuration().configure(); // 2.创建SessionFactory对象:类似JDBC连接池 SessionFactory factory = configure.buildSessionFactory(); // 3.通过SessionFactory获取Session对象:类似Connection对象 Session session = factory.openSession(); // 4.手动开启事务 Transaction transaction = session.beginTransaction(); // 5.编写代码执行数据库操作 User user = new User(); user.setId(null); user.setName("admin"); user.setPassword("123"); Serializable save = session.save(user); int ret = (int) save; // 6.提交事务 if(ret > 0){ transaction.commit(); }else { transaction.rollback(); } session.close(); factory.close(); } }
加载核心配置文件
Configuration类,加载核心配置文件
- 加载hibernate.properties文件,hibernate里无法引入映射文件,所以需要手动加载映射文件
// 1.加载hibernate核心配置文件 Configuration configure = new Configuration(); configure.addResource("com/qf/entity/User.hbm.xml");//手动加载映射文件
- 加载hibernate.cfg.xml文件
// 1.加载hibernate核心配置文件 Configuration configure = new Configuration().configure();
创建SessionFactory对象
SessionFactory,相当于一个数据库连接池,是线程安全的对象,一个项目只需要创建一个SessionFactory对象
另外,SessionFactory是一个重量级的对象,所以有必要将SessionFactory的创建过程单独抽取处理
public class SessionFactoryUtil { private static Configuration cfg ; private static SessionFactory factory; static { cfg = new Configuration().configure(); factory = cfg.buildSessionFactory(); } public Session getSession(){ Session session = factory.openSession(); return session; } }
获取Session对象以及操作数据库
Session对象,相当于JDBC操作中的Connection,负责对被持久化对象进行CRUD操作,并且线程不安全,所以不能把session定义成全局的或者抽出来单独处理
- 保存方法,save方法返回的是新增记录的id,saveOrUpdate方法适合保存和修改
- 修改方法,推荐先查询再修改
- 删除方法,推荐先查询,再删除,便于级联删除
- 查询方法
- load
- get
- load方法和get方法的区别
-
查询方法 加载策略 返回结果 查不到对象的处理方式 sql发送时机 load() 延迟加载 代理对象
javassist-3.23.1-GA.jar提供的代理技术支持
ObjectNotFoundException 真正使用对象时 get() 立即加载 对象本身 null 执行到当前代码时
-
事务相关操作
Transaction,管理Hibernate中的事务
- 开启事务
Transaction transaction = session.beginTransaction();
- 提交事务
transaction.commit();
- 回滚事务
transaction.rollback();
其他的API
Query
传递的参数是HQL语句,是面向对象的查询,返回的是一个对象的集合
String sql = "from User where id < ? and name like ?";
- 这里User是对象,id和name是对象的属性
query.setInteger(0, 10);和query.setString(1, "%ad%");是设置HQL中的"?"参数值(索引位置从0开始)
简单查询
@Test public void query() { Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); String sql = "from User where id < ? and name like ?"; Query query = session.createQuery(sql); query.setInteger(0, 10); query.setString(1, "%ad%"); List<User> list = query.list(); for (User user : list) { System.out.println(user); } tx.commit(); session.close();
----------------------------------console----------------------------------
Hibernate: select user0_.id as id1_0_, user0_.name as name2_0_, user0_.password as password3_0_ from user user0_ where user0_.id<? and ( user0_.name like ? ) User [id=3, name=admin, password=123] User [id=4, name=admin, password=123] User [id=8, name=admin, password=123]
分页查询
- query.setFirstResult(2):从第几条记录开始查询
- query.setMaxResults(3):本页一共查询多少条记录
@Test public void query() { Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); String sql = "from User"; Query query = session.createQuery(sql); query.setFirstResult(2); query.setMaxResults(3); List<User> list = query.list(); for (User user : list) { System.out.println(user); } tx.commit(); session.close(); }
----------------------------------console----------------------------------
Hibernate: select user0_.id as id1_0_, user0_.name as name2_0_, user0_.password as password3_0_ from user user0_ limit ?, ? User [id=3, name=admin, password=123] User [id=4, name=admin, password=123] User [id=5, name=hz, password=0]
Criteria
Query By Criteria:条件查询
完全面向对象的查询方式
- c.add(Restrictions.like("name", "%ad%")):这里的"name"是属性名,"%ad%"是参数值
- 返回的是一个对象的集合
查询user表中id>3并且名字中含有ad的记录
@Test public void criteria() { Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); //Criteria c = session.createCriteria("com.qf.entity.User"); Criteria c = session.createCriteria(User.class); c.add(Restrictions.like("name", "%ad%")); c.add(Restrictions.gt("id", 3)); List<User> list = c.list(); for (User user : list) { System.out.println(user); } tx.commit(); session.close(); }
----------------------------------console----------------------------------
select this_.id as id1_0_0_, this_.name as name2_0_0_, this_.password as password3_0_0_ from user this_ where this_.name like ? and this_.id>? User [id=4, name=admin, password=123] User [id=8, name=admin, password=123]
SQLQuery
接收的是SQL语句,返回的是Object[]的集合
查询user表中id>3并且名字中含有ad的记录
@Test public void SqlQuery() { Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); String sql = "select * from user where id>? and name like ?"; SQLQuery query = session.createSQLQuery(sql); query.setInteger(0, 3); query.setString(1, "%ad%"); List<Object[]> list = query.list(); for (Object[] objects : list) { System.out.println(Arrays.toString(objects)); } tx.commit(); session.close(); }
----------------------------------console----------------------------------
Hibernate: select * from user where id>? and name like ? [4, admin, 123] [8, admin, 123]