分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

11-hibernate,单表GRUD操作实例

发布时间:2023-09-06 01:24责任编辑:熊小新关键词:暂无标签

1,save

2,update

3,delete

4,get/load(查询单个纪录)

实例代码:

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.sql.Blob;import java.util.Date;import org.hibernate.Hibernate;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.junit.After;import org.junit.Before;import org.junit.Test;//测试类public class StudentsTest { ???????private SessionFactory sessionFactory; ???private Session session; ???private Transaction transaction; ???@Before ???public void init() ???{ ???????//创建配置对象 ???????Configuration config=new Configuration().configure(); ???????config.addClass(Students.class);//这个需要加上(视频里面没有) ???????//创建服务注册对象。 ???????ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder() ???????????????.applySettings(config.getProperties()).build(); //通过config.getProperties()读取配置文档。 ???????//创建会话工厂对象 ???????sessionFactory=config.buildSessionFactory(serviceRegistry); ???????//创建会话对象 ???????session=sessionFactory.openSession(); ???????//开启事务 ???????transaction=session.beginTransaction(); ???} ???@After ???public void destory() ???{ ???????transaction.commit();//提交事务 ???????session.close();//关闭会话 ???????sessionFactory.close();//关闭会话工厂 ???} ???????@Test ???public void testSaveStudents() ???{ ???????Students s=new Students(); ???????s.setSname("张三丰"); ???????s.setGender("男"); ???????Address address=new Address("710069","0289923282","西安市"); ???????s.setAddress(address); ???????????s.setBirthday(new Date()); ???????session.save(s);//保存对象进入数据库 ???} ???@Test ???//get查询方法 ???public void testGetStudents() ???{ ???????Students s=session.get(Students.class, 1); ???????System.out.println(s); ???} ???@Test ???//load查询方法 ???public void testLoadStudents() ???{ ???????Students s=session.load(Students.class, 1); ???????System.out.println(s); ???} ???????@Test ???//更新方法 ???public void testUpdateStudents() ???{ ???????Students s=session.get(Students.class, 1); ???????s.setGender("女"); ???????session.update(s); ???} ???@Test ???//删除方法 ???public void testDeleteStudents() ???{ ???????Students s=session.load(Students.class, 1); ???????session.delete(s); ???}}

测试结果:

get

 load

update

delete

get与load区别

1,get在调用之后离开发送sql语句,不考虑缓存,返回持久化对象。

2,load方法在调用后返回一个代理对象。

该代理对象只保存了实体对象的ID,直到使用对象的非主键属性时才会发出sql语句,比如打印输出时候,会调用发出SQL。

3,如果查询数据库不存在的数据,get方法返回null,load方法抛出异常。

11-hibernate,单表GRUD操作实例

原文地址:http://www.cnblogs.com/alsf/p/7821720.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved