hibernate之CRUD操作

CRUD是指在做计算处理时的增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写.

下面列举实例来讲解这几个操作:

实体类:

package com.oumyye.model;public class Student {private long id;private String name;private Class c;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Class getC() {return c;}public void setC(Class c) {this.c = c;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + "]";}}
package com.oumyye.model;import java.util.HashSet;
import java.util.Set;public class Class {private long id;private String name;private Set<Student> students=new HashSet<Student>();public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}}

映射文件:

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.oumyye.model"><class name="Student" table="t_student"><id column="stuId" name="id"><generator class="native"/></id><property column="stuName" generated="never" lazy="false" name="name"/><many-to-one cascade="save-update" class="com.oumyye.model.Class"column="classId" name="c"/></class>
</hibernate-mapping>
Class.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.oumyye.model"><class name="Class" table="t_class"><id column="classId" name="id"><generator class="native"/></id><property column="className" generated="never" lazy="false" name="name"/><set cascade="delete" inverse="true" name="students" sort="unsorted"><key column="classId"/><one-to-many class="com.oumyye.model.Student"/></set></class>
</hibernate-mapping>

工具类:可以有myeclipse生成

package com.oumyye.util;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;/*** Configures and provides access to Hibernate sessions, tied to the* current thread of execution.  Follows the Thread Local Session* pattern, see {@link http://hibernate.org/42.html }.*/
public class HibernateSessionFactory {/** * Location of hibernate.cfg.xml file.* Location should be on the classpath as Hibernate uses  * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session.   */private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();private static org.hibernate.SessionFactory sessionFactory;private static Configuration configuration = new AnnotationConfiguration();    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static String configFile = CONFIG_FILE_LOCATION;static {try {configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();}}private HibernateSessionFactory() {}/*** Returns the ThreadLocal Session instance.  Lazy initialize* the <code>SessionFactory</code> if needed.**  @return Session*  @throws HibernateException*/public static Session getSession() throws HibernateException {Session session = (Session) threadLocal.get();if (session == null || !session.isOpen()) {if (sessionFactory == null) {rebuildSessionFactory();}session = (sessionFactory != null) ? sessionFactory.openSession(): null;threadLocal.set(session);}return session;}/***  Rebuild hibernate session factory**/public static void rebuildSessionFactory() {try {configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();}}/***  Close the single hibernate session instance.**  @throws HibernateException*/public static void closeSession() throws HibernateException {Session session = (Session) threadLocal.get();threadLocal.set(null);if (session != null) {session.close();}}/***  return session factory**/public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;}/***  return session factory**    session factory will be rebuilded in the next call*/public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;}/***  return hibernate configuration**/public static Configuration getConfiguration() {return configuration;}}

配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!--数据库连接设置 --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/mytest</property><property name="connection.username">root</property><property name="connection.password">root</property><!-- 方言 --><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 控制台显示SQL --><property name="show_sql">true</property><!-- 自动更新表结构 --><property name="hbm2ddl.auto">update</property><mapping resource="com/oumyye/model/Class.hbm.xml" /><mapping resource="com/oumyye/model/Student.hbm.xml" /></session-factory></hibernate-configuration>

测试类

package com.oumyye.service;import java.util.Iterator;
import java.util.Set;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;import com.oumyye.model.Class;
import com.oumyye.model.Student;
import com.oumyye.util.HibernateSessionFactory;public class StudentTest {private SessionFactory sessionFactory=HibernateSessionFactory.getSessionFactory();private Session session;@Beforepublic void setUp() throws Exception {session=sessionFactory.openSession(); // 生成一个sessionsession.beginTransaction(); // 开启事务
    }@Afterpublic void tearDown() throws Exception {session.getTransaction().commit(); // 提交事务session.close(); // 关闭session
    }@Testpublic void testSaveClassAndStudent() {Class c=new Class();c.setName("08计本");Student s1=new Student();s1.setName("张三");s1.setC(c);Student s2=new Student();s2.setName("李四");s2.setC(c);session.save(s1);session.save(s2);}@Testpublic void testLoadClass(){// Class c=(Class)session.load(Class.class, Long.valueOf(2));Class c=(Class)session.load(Class.class, Long.valueOf(1));System.out.println(c.getStudents());}@Testpublic void testGetClass(){// Class c=(Class)session.get(Class.class, Long.valueOf(2));Class c=(Class)session.get(Class.class, Long.valueOf(1));System.out.println(c.getStudents());}@Testpublic void testUpdateClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();c.setName("08计算机本科2");session2.update(c);session2.getTransaction().commit(); // 提交事务
        session2.close();}<!--更新-->@Testpublic void testSaveOrUpdateClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();c.setName("08计算机本科3");Class c2=new Class();c2.setName("09计算机本科3");session2.saveOrUpdate(c);session2.saveOrUpdate(c2);session2.getTransaction().commit(); // 提交事务
        session2.close();}@Testpublic void testMergeClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();Class c2=(Class)session2.get(Class.class, Long.valueOf(1));c.setName("08计算机本科4");session2.merge(c);session2.getTransaction().commit(); // 提交事务
        session2.close();}<!--删除-->@Testpublic void testDeleteStudent(){Student student=(Student)session.load(Student.class, Long.valueOf(1));session.delete(student);}
}
package com.oumyye.service;import java.util.Iterator;
import java.util.Set;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;import com.oumyye.model.Class;
import com.oumyye.model.Student;
import com.oumyye.util.HibernateSessionFactory;public class StudentTest {private SessionFactory sessionFactory=HibernateSessionFactory.getSessionFactory();private Session session;@Beforepublic void setUp() throws Exception {session=sessionFactory.openSession(); // 生成一个sessionsession.beginTransaction(); // 开启事务
    }@Afterpublic void tearDown() throws Exception {session.getTransaction().commit(); // 提交事务session.close(); // 关闭session
    }@Testpublic void testSaveClassAndStudent() {Class c=new Class();c.setName("08计本");Student s1=new Student();s1.setName("张三");s1.setC(c);Student s2=new Student();s2.setName("李四");s2.setC(c);session.save(s1);session.save(s2);}@Testpublic void testLoadClass(){// Class c=(Class)session.load(Class.class, Long.valueOf(2));Class c=(Class)session.load(Class.class, Long.valueOf(1));System.out.println(c.getStudents());}@Testpublic void testGetClass(){// Class c=(Class)session.get(Class.class, Long.valueOf(2));Class c=(Class)session.get(Class.class, Long.valueOf(1));System.out.println(c.getStudents());}@Testpublic void testUpdateClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();c.setName("08计算机本科2");session2.update(c);session2.getTransaction().commit(); // 提交事务
        session2.close();}<!--更新-->@Testpublic void testSaveOrUpdateClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();c.setName("08计算机本科3");Class c2=new Class();c2.setName("09计算机本科3");session2.saveOrUpdate(c);session2.saveOrUpdate(c2);session2.getTransaction().commit(); // 提交事务
        session2.close();}@Testpublic void testMergeClass(){Session session1=sessionFactory.openSession();session1.beginTransaction();Class c=(Class)session1.get(Class.class, Long.valueOf(1));session1.getTransaction().commit(); // 提交事务
        session1.close();Session session2=sessionFactory.openSession();session2.beginTransaction();Class c2=(Class)session2.get(Class.class, Long.valueOf(1));c.setName("08计算机本科4");session2.merge(c);session2.getTransaction().commit(); // 提交事务
        session2.close();}<!--删除-->@Testpublic void testDeleteStudent(){Student student=(Student)session.load(Student.class, Long.valueOf(1));session.delete(student);}
}

Session的入门常用方法

  • Query query = session.createQuery(hql):利用hql查询语句查询;
  • Criteria critera = session.createCriteria(Class clazz);
  • (3)Transaction tx = session.beginTransaction();     //开始事务;tx.commit()提交事务;
  • session.close();//关闭Session,此后被session管理的持久化对象变为脱管状态;
  • session.save(Object obj);    //添加
  • session.update(Object obj);     //更新
  • session.delete(Object obj);    //删除
  • Object obj = session.get(Class clazz,Serialiazble id);    //根据主键查找记录并返回;
  • Object obj = session.load(Class clazz,Serializable id);    //和get方法效果一样,但是是懒加载,即在不使用他之前他不会返回对象;

转载于:https://www.cnblogs.com/zhujiabin/p/4529851.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/492207.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

谷歌自动驾驶专利大曝光!

来源&#xff1a;智车科技摘要&#xff1a;本文仅针对其中自动驾驶汽车部分&#xff0c;说明自动驾驶的分级&#xff0c;再以Google为例&#xff0c;说明其发展的自动驾驶汽车和相关技术&#xff0c;分析及说明Google与自动驾驶汽车相关的发明专利及设计专利的布局&#xff0c;…

(Python代码)通过视差图获取图片中不同物体的高度比

1、原理 可以推出不同物体的高度比可以通过如下公式得到&#xff1a; 是左边指定物体的高度&#xff08;图片中尺寸&#xff09; 是右边指定物体的高度&#xff08;图片中尺寸&#xff09; 是左边指定物体的平均视差值 是右边指定物体的平均视差值 2、代码逻辑框图 3、代码详解…

Nginx 安装与启动

安装第一种安装方式&#xff1a;CentOS 7下配置 yum 安装 Nginx。按照官方的安装实例&#xff1a;https://www.nginx.com/resources/admin-guide/第一步&#xff0c;在/etc/yum.repos.d/目录下创建一个源配置文件nginx.repo&#xff1a;cd /etc/yum.repos.d/vim nginx.repo 填写…

一文读懂生物医学领域的传感器

来源&#xff1a;传感器技术摘要&#xff1a;生物医学传感器是生物医学科学和技术的尖兵&#xff0c;生物医学研究的正确结论有赖于生物医学传感器的正确测量。而传感器是一门十分综合的科学和技术。现代传感器的物理模型如图所示&#xff1a;对于传统被测量而言&#xff0c;敏…

训练数据的分布对F-measure, recall 和 precision的影响

1、 Precision, recall and F-measure&#xff08;f1-score&#xff09; 2、思路 数据集&#xff1a;手写数字集 从训练集中抽取数据&#xff0c;保证每种label的数量一致&#xff0c;使用SVM 或ANN模型训练新数据集。按照高斯分布抽取新数据&#xff0c; 再次使用SVM 或ANN模…

稀疏矩阵的压缩存储--十字链表(转载)

稀疏矩阵的压缩存储--十字链表&#xff08;转载&#xff09;<?xml version"1.0" encoding"UTF-8"?> 来自为知笔记(Wiz)转载于:https://www.cnblogs.com/ZhangJinkun/p/4531626.html

不可思议的数字:互联网每天到底能产生多少数据?

来源&#xff1a;资本实验室随着互联网、传感器&#xff0c;以及各种数字化终端设备的普及&#xff0c;一个万物互联的世界正在成型。同时&#xff0c;随着数据呈现出爆炸式的指数级增长&#xff0c;数字化已经成为构建现代社会的基础力量&#xff0c;并推动着我们走向一个深度…

(Matlab问题解决)运行matlab程序后,工作区不能显示变量

运行matlab程序&#xff0c;想查看工作区的变量&#xff0c;发现变量无法显示。 原代码特点&#xff1a; 代码中的主函数是以 function main()开头没有end结尾&#xff0c;子函数以function开口&#xff0c;没有end 结尾。 修改方式&#xff1a; 主函数中去掉function main…

redis 安装并设置为开机启动服务

安装 1.下载redis,wget http://download.redis.io/releases/redis-3.0.1.tar.gz 解压&#xff1a;tar zxvf redis3.0.1.tar.gz cd redis3.0.1 make make test 报错&#xff0c;提示需要安装tcl&#xff0c; wget http://downloads.sourceforge.net/tcl/tcl8.6.1-src.tar.gz 安装…

任正非:华为5G芯片用在iPhone上?我持开放态度

来源&#xff1a;机器之心摘要&#xff1a;外媒最近频传的「华为同意卖5G基带给苹果」&#xff0c;让科技界的人们浮想联翩。刚刚&#xff0c;华为终于有了较为官方的回应&#xff1a;华为总裁任正非在接受CNBC的时候表示&#xff0c;华为对于出售5G芯片给苹果用于iPhone「持开…

string.Format格式化输出

staticstring Format (string format,object arg0):将指定字符串中的一个或多个格式项替换为指定对象的字符串表示形式 (1)格式化货币&#xff08;跟系统的环境有关&#xff0c;中文系统默认格式化人民币&#xff0c;英文系统格式化美元&#xff09;string.Format("{0: C}…

阿里120页PPT诠释国家“智能+”战略

未来智能实验室是人工智能学家与科学院相关机构联合成立的人工智能&#xff0c;互联网和脑科学交叉研究机构。未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评测体系&#xff0c;开展世界人工智能智商评测&#xff1b;开展互联网&#xff08;城市&#xff09;云…

边缘检测

1、边缘的特征 先看一张实物图和边缘图 边缘是图片中灰度变化最快的地方。下图清楚地显示了最简单的一种情况。既然找变化最快的地方&#xff0c;可以通过导数来求解边缘 2、图片的导数 一张数字图片F[x,y], 其x方向导数可定义为&#xff1a; 3、图片的梯度 3.1 图片的梯度相…

黑马程序程序员基础测试(二)

2、 编写程序计算122232....1002的和. 我觉得这题的难点是在你如何快速寻找到累加的次数。和每次累加的增量。 package com.itheima;public class Text2 {/*** 2、 编写程序计算122232....1002的和.* author tianshenjiaoao* param args*/public static void main(String[] arg…

边缘计算: 与5G同行,开拓蓝海新市场

来源&#xff1a;中银国际摘要&#xff1a;随着日渐成熟的SDN/NFV、大数据、人工智能等技术&#xff0c;5G网络将成为各行业数字化转型的关键基础设施。边缘计算技术作为5G网络架构中核心的一环&#xff0c;顺随运营商边缘机房智能化改造的趋势&#xff0c;致力于解决5G网络对于…

图像重采样

图像重采样包含两种情形&#xff0c;一种是下采样&#xff08;downsampling&#xff09;&#xff0c;把图像变小&#xff1b;另一种是上采样&#xff08;upsampling)&#xff0c;把图像变大。 1、次级采样&#xff08;sub-sampling&#xff09; 每隔一个&#xff0c;扔掉行和…

haha

转载于:https://www.cnblogs.com/izxcheng/p/4539888.html

裸机开发(1)-汇编基础

文章目录 GNU汇编语法常用汇编指令处理器内部数据传输指令存储器访问指令压栈和出栈指令跳转指令算术指令逻辑运算指令实战 函数发生调用时&#xff0c;需要进行线程保护&#xff0c;简单来说&#xff0c;就是先进行压栈操作&#xff0c;将调用函数参数、返回值等存到R0-15寄存…

脑科学研究:对于学习来说,休息可能与练习同样重要...

来源&#xff1a;神经科技近日&#xff0c;在针对健康志愿者的的一项研究中&#xff0c;美国国立卫生研究院&#xff08;NIH&#xff09;的研究人员发现&#xff0c;大脑可能会通过短暂的休息来巩固我们几秒钟前刚练习过的新技能的记忆。该研究结果强调了早期休息在学习中可能发…

Harris 角点检测(Harris corner detection)

在许多应用中&#xff0c;会运用到特征提取。 比如&#xff0c;把下方两张图片缝合成一张图片。哪么从哪些地方开始缝合呢&#xff1f;这些地方可以通过特征提取找到。 1、特征 图片上的特征点应该具有怎样的特性&#xff1f; a. 图片上的特征点不随图片的变化&#xff08;平…