• (五)Hibernate 操作对象


    所有项目导入对应的hibernate的jar包、mysql的jar包和添加每次都需要用到的HibernateUtil.java

    第一节:Hibernate 中四种对象状态

    临时状态(transient):刚用new 语句创建,还没有被持久化,并且不处于Sesssion 的缓存中。处于临时状态的Java 对象被称为临时对象。


    持久化状态(persistent):已经被持久化,并且加入到Session 的缓存中。处于持久化状态的Java 对象被称为持久化对象。


    删除状态(removed):不再处于Session 的缓存中,并且Session 已经计划将其从数据库中删除。处于删除状态的Java 对象被称为删除对象。


    游离状态(detached):已经被持久化,但不再处于Session 的缓存中。处于游离状态的Java 对象被称为游离对象。

     

     

     

     

    例子:

    hibernate.cfg.xml

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7 
     8     <session-factory>
     9 
    10         <!--数据库连接设置 -->
    11         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    12         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    13         <property name="connection.username">root</property>
    14         <property name="connection.password">123456</property>
    15 
    16        
    17         <!-- 方言 -->
    18         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    19     
    20         <!-- 控制台显示SQL -->
    21         <property name="show_sql">true</property>
    22 
    23         <!-- 自动更新表结构 -->
    24         <property name="hbm2ddl.auto">update</property>
    25         
    26           <mapping resource="com/wishwzp/model/Student.hbm.xml"/>
    27           
    28           <mapping resource="com/wishwzp/model/Class.hbm.xml"/>
    29 
    30     </session-factory>
    31 
    32 </hibernate-configuration>

    Class.java

     1 package com.wishwzp.model;
     2 
     3 public class Class {
     4 
     5     private long id;
     6     private String name;
     7     
     8     public long getId() {
     9         return id;
    10     }
    11     public void setId(long id) {
    12         this.id = id;
    13     }
    14     public String getName() {
    15         return name;
    16     }
    17     public void setName(String name) {
    18         this.name = name;
    19     }
    20     
    21     
    22 }

    Class.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Class" table="t_class">
     9         <id name="id" column="classId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="className"></property>
    14     </class>
    15 
    16 </hibernate-mapping>

    Student.java

     1 package com.wishwzp.model;
     2 
     3 public class Student {
     4 
     5     private long id;
     6     private String name;
     7     private Class c;
     8     
     9     public long getId() {
    10         return id;
    11     }
    12     public void setId(long id) {
    13         this.id = id;
    14     }
    15     public String getName() {
    16         return name;
    17     }
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21     
    22     
    23     public Class getC() {
    24         return c;
    25     }
    26     public void setC(Class c) {
    27         this.c = c;
    28     }
    29     @Override
    30     public String toString() {
    31         return "Student [id=" + id + ", name=" + name + "]";
    32     }
    33     
    34     
    35 }

    Student.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <many-to-one name="c" column="classId" class="com.wishwzp.model.Class" cascade="save-update"></many-to-one>
    16     </class>
    17 
    18 </hibernate-mapping>

    StudentTest.java

     1 package com.wishwzp.service;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 
     6 import com.wishwzp.model.Class;
     7 import com.wishwzp.model.Student;
     8 import com.wishwzp.util.HibernateUtil;
     9 
    10 public class StudentTest {
    11     
    12     public static void main(String[] args) {
    13         SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    14         Session session=sessionFactory.openSession(); // 生成一个session
    15         session.beginTransaction(); // 开启事务
    16         
    17         Class c1=new Class(); // 临时对象1
    18         c1.setName("08计本");
    19         
    20         Class c2=new Class();  // 临时对象2
    21         c2.setName("09计本");
    22         
    23         session.save(c1); // 持久化对象
    24         session.save(c2); // 持久化对象
    25         
    26         session.delete(c2); // 删除对象
    27         
    28         session.getTransaction().commit(); // 提交事务
    29         session.close(); // 关闭session
    30         
    31         System.out.println(c1.getName()); // 游离对象
    32         System.out.println(c2.getName()); // 删除对象
    33     }
    34 }

    结果显示:

     第二节:Session 常用方法讲解

    1,save()方法将一个临时对象转变成持久化对象;

    2,load()方法VS get()方法

    都是根据OID 从数据库中加载一个持久化对象。

    区别1:假如数据库中不存在与OID 对应的记录,Load()方法会抛出异常,而get()方法返回null;

    区别2:load 方法默认采用延迟加载策略,get 方法采用立即检索策略;

    2,update()方法将一个游离对象转变为持久化对象;

    3,saveOrUpdate()方法包含了save()和update()方法;

    4,merge()方法,合并对象;

    5,delete()方法,删除对象;

     例子:

    hibernate.cfg.xml

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7 
     8     <session-factory>
     9 
    10         <!--数据库连接设置 -->
    11         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    12         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    13         <property name="connection.username">root</property>
    14         <property name="connection.password">123456</property>
    15 
    16        
    17         <!-- 方言 -->
    18         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    19     
    20         <!-- 控制台显示SQL -->
    21         <property name="show_sql">true</property>
    22 
    23         <!-- 自动更新表结构 -->
    24         <property name="hbm2ddl.auto">update</property>
    25         
    26           <mapping resource="com/wishwzp/model/Student.hbm.xml"/>
    27           
    28           <mapping resource="com/wishwzp/model/Class.hbm.xml"/>
    29 
    30     </session-factory>
    31 
    32 </hibernate-configuration>

    Class.java

     1 package com.wishwzp.model;
     2 
     3 import java.util.HashSet;
     4 import java.util.Set;
     5 
     6 public class Class {
     7 
     8     private long id;
     9     private String name;
    10     private Set<Student> students=new HashSet<Student>();
    11     
    12     public long getId() {
    13         return id;
    14     }
    15     public void setId(long id) {
    16         this.id = id;
    17     }
    18     public String getName() {
    19         return name;
    20     }
    21     public void setName(String name) {
    22         this.name = name;
    23     }
    24     public Set<Student> getStudents() {
    25         return students;
    26     }
    27     public void setStudents(Set<Student> students) {
    28         this.students = students;
    29     }
    30     
    31     
    32 }

    Class.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Class" table="t_class">
     9         <id name="id" column="classId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="className"></property>
    14         
    15         <set name="students" cascade="delete" inverse="true">
    16             <key column="classId"></key>
    17             <one-to-many class="com.wishwzp.model.Student"/>
    18         </set>
    19     </class>
    20 
    21 </hibernate-mapping>

    Student.java

     1 package com.wishwzp.model;
     2 
     3 public class Student {
     4 
     5     private long id;
     6     private String name;
     7     private Class c;
     8     
     9     public long getId() {
    10         return id;
    11     }
    12     public void setId(long id) {
    13         this.id = id;
    14     }
    15     public String getName() {
    16         return name;
    17     }
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21     
    22     
    23     public Class getC() {
    24         return c;
    25     }
    26     public void setC(Class c) {
    27         this.c = c;
    28     }
    29     @Override
    30     public String toString() {
    31         return "Student [id=" + id + ", name=" + name + "]";
    32     }
    33     
    34     
    35 }

    Studnet.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <many-to-one name="c" column="classId" class="com.wishwzp.model.Class" cascade="save-update"></many-to-one>
    16     </class>
    17 
    18 </hibernate-mapping>

    StudentTest.java

      1 package com.wishwzp.service;
      2 
      3 import java.util.Iterator;
      4 import java.util.Set;
      5 
      6 import org.hibernate.Session;
      7 import org.hibernate.SessionFactory;
      8 import org.junit.After;
      9 import org.junit.Before;
     10 import org.junit.Test;
     11 
     12 import com.wishwzp.model.Class;
     13 import com.wishwzp.model.Student;
     14 import com.wishwzp.util.HibernateUtil;
     15 
     16 public class StudentTest {
     17 
     18     private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
     19     private Session session;
     20     
     21     @Before
     22     public void setUp() throws Exception {
     23         session=sessionFactory.openSession(); // 生成一个session
     24         session.beginTransaction(); // 开启事务
     25     }
     26 
     27     @After
     28     public void tearDown() throws Exception {
     29          session.getTransaction().commit(); // 提交事务
     30          session.close(); // 关闭session
     31     }
     32 
     33     //save()方法
     34     @Test
     35     public void testSaveClassAndStudent() {
     36         Class c=new Class();
     37         c.setName("08计本");
     38        
     39         Student s1=new Student();
     40         s1.setName("张三");
     41         s1.setC(c);
     42         
     43         Student s2=new Student();
     44         s2.setName("李四");
     45         s2.setC(c);
     46        
     47         session.save(s1);
     48         session.save(s2);
     49         
     50     }
     51     
     52     //load()方法和get()方法的区别
     53     //Load()方法会抛出异常,而get()方法返回null;
     54     @Test
     55     public void testLoadClass(){
     56         // Class c=(Class)session.load(Class.class, Long.valueOf(2));
     57         Class c=(Class)session.load(Class.class, Long.valueOf(1));
     58         System.out.println(c.getStudents());
     59     }
     60     
     61     
     62     @Test
     63     public void testGetClass(){
     64         // Class c=(Class)session.get(Class.class, Long.valueOf(2));
     65         Class c=(Class)session.get(Class.class, Long.valueOf(1));
     66         System.out.println(c.getStudents());
     67     }
     68     
     69     //update()方法
     70     @Test
     71     public void testUpdateClass(){
     72         Session session1=sessionFactory.openSession();
     73         session1.beginTransaction();
     74         Class c=(Class)session1.get(Class.class, Long.valueOf(1));
     75         session1.getTransaction().commit(); // 提交事务
     76         session1.close();
     77         
     78         Session session2=sessionFactory.openSession();
     79         session2.beginTransaction();
     80         c.setName("08计算机本科2");
     81         session2.update(c);
     82         session2.getTransaction().commit(); // 提交事务
     83         session2.close();
     84     }
     85     
     86     //saveOrUpdate()方法
     87     @Test
     88     public void testSaveOrUpdateClass(){
     89         Session session1=sessionFactory.openSession();
     90         session1.beginTransaction();
     91         Class c=(Class)session1.get(Class.class, Long.valueOf(1));
     92         session1.getTransaction().commit(); // 提交事务
     93         session1.close();
     94         
     95         Session session2=sessionFactory.openSession();
     96         session2.beginTransaction();
     97         c.setName("08计算机本科3");
     98         
     99         Class c2=new Class();
    100         c2.setName("09计算机本科3");
    101         session2.saveOrUpdate(c);
    102         session2.saveOrUpdate(c2);
    103         session2.getTransaction().commit(); // 提交事务
    104         session2.close();
    105     }
    106     
    107     //merge()方法
    108     @Test
    109     public void testMergeClass(){
    110         Session session1=sessionFactory.openSession();
    111         session1.beginTransaction();
    112         Class c=(Class)session1.get(Class.class, Long.valueOf(1));
    113         session1.getTransaction().commit(); // 提交事务
    114         session1.close();
    115         
    116         Session session2=sessionFactory.openSession();
    117         session2.beginTransaction();
    118         
    119         Class c2=(Class)session2.get(Class.class, Long.valueOf(1));
    120         c.setName("08计算机本科4");
    121     
    122         session2.merge(c);
    123 
    124         session2.getTransaction().commit(); // 提交事务
    125         session2.close();
    126     }
    127     
    128     //delete()方法
    129     @Test
    130     public void testDeleteStudent(){
    131         Student student=(Student)session.load(Student.class, Long.valueOf(1));
    132         session.delete(student);
    133     }
    134 }
  • 相关阅读:
    使用js固定div的高度
    iphone开发常用编码
    php mssql扩展SQL查询中文字段名解决方法
    Android带进度条文件上传
    PHP中替换换行符
    Android Timer计时器
    语法:MySQL中INSERT INTO SELECT的使用
    mysql的多表关联更新怎么写?
    Page Utility
    How do use CheckBoxList Utility
  • 原文地址:https://www.cnblogs.com/wishwzp/p/5481238.html
Copyright © 2020-2023  润新知