zoukankan      html  css  js  c++  java
  • Hibernate CRUD操作

    版权声明:本文为博主原创文章,如需转载请标注转载地址

    博客地址:http://www.cnblogs.com/caoyc/p/5594789.html 

    对于Hibernate的增删改查,我们还是用一个案例来说明

    下面是整个项目的目录结构:

    一、com.mypro.domain包

    1、封装person域模型

     1 package com.mypro.domain;
     2 
     3 public class Person {
     4 
     5     private int id;
     6     private String name;
     7     private int age;
     8     private String gender;
     9     public int getId() {
    10         return id;
    11     }
    12     public void setId(int 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     public int getAge() {
    22         return age;
    23     }
    24     public void setAge(int age) {
    25         this.age = age;
    26     }
    27     public String getGender() {
    28         return gender;
    29     }
    30     public void setGender(String gender) {
    31         this.gender = gender;
    32     }
    33     @Override
    34     public String toString() {
    35         return "Person [id=" + id + ", name=" + name + ", age=" + age
    36                 + ", gender=" + gender + "]";
    37     }
    38     public Person(int id, String name, int age, String gender) {
    39         super();
    40         this.id = id;
    41         this.name = name;
    42         this.age = age;
    43         this.gender = gender;
    44     }
    45     public Person() {
    46         super();
    47     }
    48     
    49 }
    Person.java

    2、定义QueryResult用来返回分页查询结果集以及表总所有记录数据的封装

     1 package com.mypro.domain;
     2 
     3 import java.util.List;
     4 
     5 public class QueryResult {
     6 
     7     //返回数据库中某表总的记录数
     8     private long count;
     9     //返回结果集
    10     private List list;
    11     public long getCount() {
    12         return count;
    13     }
    14     public void setCount(long count) {
    15         this.count = count;
    16     }
    17     public List getList() {
    18         return list;
    19     }
    20     public void setList(List list) {
    21         this.list = list;
    22     }
    23     public QueryResult(long count, List list) {
    24         super();
    25         this.count = count;
    26         this.list = list;
    27     }
    28     public QueryResult() {
    29         super();
    30     }
    31     
    32 }
    QueryResult.java

    3、定义Person类和数据库表的映射关系

     1 <?xml version="1.0"?>
     2 
     3 <!DOCTYPE hibernate-mapping PUBLIC
     4         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     5         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
     6 <hibernate-mapping package="com.mypro.domain">
     7     <class name="Person" table="person">
     8         <id name="id" column="Id" type="int">
     9             <generator class="native"></generator>
    10         </id>
    11         <property name="name" column="name" type="string"></property>
    12         <property name="age" column="Age" type="int"></property>
    13         <property name="gender" column="Gender" type="string"></property>
    14     </class>
    15 </hibernate-mapping>
    Person.hbm.xml

    二、com.mypro.dao包

    1、定一个IPerson的接口,以及接口需要实现的方法

     1 package com.mypro.dao;
     2 
     3 import java.util.List;
     4 
     5 import com.mypro.domain.Person;
     6 import com.mypro.domain.QueryResult;
     7 
     8 public interface IPerson {
     9 
    10     /**
    11      * 添加Person
    12      * @param person
    13      */
    14      void add(Person person);
    15      
    16      /**
    17       * 通过ID删除Person
    18       * @param id
    19       */
    20      void delete(int id);
    21      
    22      /**
    23       * 修改Person信息
    24       * @param person
    25       */
    26      void update(Person person);
    27      
    28      /**
    29       * 通过ID获取Person
    30       * @param id
    31       * @return
    32       */
    33      Person get(int id);
    34      
    35      /**
    36       * 获取所有的Person
    37       * @return List集合
    38       */
    39      List<Person> getAll();
    40      
    41      /**
    42       * 分页查询显示
    43       * @param firstResult 第一条记录从哪里开始
    44       * @param maxResults 最多包含多少条记录
    45       * @return 该返回值包含了一个表的总记录数和一个List结果集
    46       */
    47       QueryResult query(int firstResult,int maxResults);
    48 
    49 }
    IPerson.java

    三、com.mypro.util包

    1、定一个HibernateUtils工具类,该类封装了SessionFactory对象

     1 package com.mypro.util;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 import org.hibernate.cfg.Configuration;
     6 
     7 public class HibernateUtils {
     8 
     9     //声明一个静态变量,并在静态代码块中给该对象赋值
    10     private static SessionFactory sessionFactory;
    11     static{
    12         /*方式一
    13         Configuration cfg=new Configuration();
    14         cfg.configure("hibernate.cfg.xml"); //加载指定位置的配置
    15         sessionFactory=cfg.buildSessionFactory();*/
    16         
    17         /*方式二:当hibernate的主配置文件名称为hibernate.cfg.xml时,且该文件在类的根目录下时,当cfg.configure时可以省略参数
    18         Configuration cfg=new Configuration();
    19         cfg.configure(); //加载默认配置文件
    20         sessionFactory=cfg.buildSessionFactory();*/
    21         
    22         //方法三 :由于cfg.configure()方法返回的依然是Configuration对象,所以该方法更进一步精简为
    23         sessionFactory=new Configuration()
    24             .configure()
    25             .buildSessionFactory();
    26     }
    27     
    28     /**
    29      * 获取SessionFactory工厂
    30      * @return
    31      */
    32     public static SessionFactory getSessionFactory(){
    33         return sessionFactory;
    34     }
    35     
    36     /**
    37      * 获取返回一个打开的Session
    38      * @return
    39      */
    40     public static Session openSession(){
    41         return sessionFactory.openSession();
    42     }
    43 }
    HibernateUtils.java

    四、com.mypro.dao.impl包

    该包主要实现com.mypro.dao下的接口

    1、实现IPerson接口

      1 package com.mypro.dao.impl;
      2 
      3 import java.util.List;
      4 
      5 import org.hibernate.Query;
      6 import org.hibernate.Session;
      7 import org.hibernate.Transaction;
      8 
      9 import com.mypro.dao.IPerson;
     10 import com.mypro.domain.Person;
     11 import com.mypro.domain.QueryResult;
     12 import com.mypro.util.HibernateUtils;
     13 
     14 public class PersonImpl implements IPerson {
     15 
     16     @Override
     17     public void add(Person person) {
     18         Session session=null;
     19         Transaction tran=null;
     20         try{
     21             session=HibernateUtils.openSession();
     22             tran=session.beginTransaction();
     23             session.save(person);
     24             tran.commit();
     25         }catch(RuntimeException e){
     26             if(tran!=null)
     27                 tran.rollback();
     28             throw e;
     29         }finally{
     30             if(session!=null)
     31                 session.close();
     32         }
     33         
     34     }
     35 
     36     @Override
     37     public void delete(int id) {
     38         Session session=null;
     39         Transaction tran=null;
     40         try{
     41             session=HibernateUtils.openSession();
     42             tran=session.beginTransaction();
     43             Person person=session.get(Person.class, id);
     44             session.delete(person);
     45             tran.commit();
     46         }catch(RuntimeException e){
     47             if(tran!=null)
     48                 tran.rollback();
     49             throw e;
     50         }finally{
     51             if(session!=null)
     52                 session.close();
     53         }
     54         
     55     }
     56 
     57     @Override
     58     public void update(Person person) {
     59         Session session=null;
     60         Transaction tran=null;
     61         try{
     62             session=HibernateUtils.openSession();
     63             tran=session.beginTransaction();
     64             session.update(person);
     65             tran.commit();
     66         }catch(RuntimeException e){
     67             if(tran!=null)
     68                 tran.rollback();
     69             throw e;
     70         }finally{
     71             if(session!=null)
     72                 session.close();
     73         }
     74         
     75     }
     76 
     77     @Override
     78     public Person get(int id) {
     79         Session session=null;
     80         try{
     81             session=HibernateUtils.openSession();
     82             return session.get(Person.class, id);
     83         }catch(RuntimeException e){
     84             throw e;
     85         }finally{
     86             if(session!=null)
     87                 session.close();
     88         }
     89     }
     90 
     91     @Override
     92     public List<Person> getAll() {
     93         Session session=null;
     94         try{
     95             session=HibernateUtils.openSession();
     96             /*方式一
     97             Query query= session.createQuery("FROM persion",,Person.class);
     98             return query.list(); */
     99             //方式二
    100             return session.createQuery("from Person").list();    //注意HSL方式要求Person为类名,属性名和类名必须完全一致,其它关键字可忽略大小写
    101         }catch(RuntimeException e){
    102             throw e;
    103         }finally{
    104             if(session!=null)
    105                 session.close();
    106         }
    107     }
    108 
    109     @Override
    110     public QueryResult query(int firstResult, int maxResults) {
    111         Session session=null;
    112         try{
    113             session=HibernateUtils.openSession();
    114             long count= (long)session.createQuery("SELECT COUNT(*) FROM Person").uniqueResult();
    115             List list=session.createQuery("FROM Person")//
    116                     .setFirstResult(firstResult)//
    117                     .setMaxResults(maxResults)
    118                     .list();
    119             return new QueryResult(count, list);
    120         }catch(RuntimeException e){
    121             throw e;
    122         }finally{
    123             if(session!=null)
    124                 session.close();
    125         }
    126     }
    127 
    128 }
    PersonImpl.java

    五、配置hibernate主配置文件

     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 <hibernate-configuration>
     6 <session-factory name="mysqldb">
     7 
     8     <!-- 配置方言:选择数据库类型 -->
     9     <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    10     
    11     <!-- 配置数据库连接信息 -->
    12     <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    13     <property name="connection.url">jdbc:mysql:///test?characterEncoding=utf8</property>
    14     <property name="connection.username">root</property>
    15     <property name="connection.password">123456</property>
    16     
    17     <!-- 允许显示sql语句 -->
    18     <property name="show_sql">true</property>
    19     <!-- 导入映射文件 -->
    20     <mapping resource="com/mypro/domain/Person.hbm.xml" />
    21 </session-factory>
    22 </hibernate-configuration>
    hibernate.cfg.xml

    六、代码测试

    1、在com.mypro.test包下PersonTest.java

     1 package com.mypro.test;
     2 
     3 import java.util.List;
     4 
     5 import org.junit.Test;
     6 
     7 import com.mypro.dao.IPerson;
     8 import com.mypro.dao.impl.PersonImpl;
     9 import com.mypro.domain.Person;
    10 import com.mypro.domain.QueryResult;
    11 
    12 public class PersonTest {
    13 
    14     private static IPerson personDao=new PersonImpl();
    15     
    16     @Test
    17     public void add(){
    18         Person person=new Person();
    19         person.setName("zhh");
    20         person.setAge(26);
    21         person.setGender("女");
    22         personDao.add(person);
    23     }
    24     
    25     @Test
    26     public void get(){
    27         Person person=personDao.get(37);
    28         System.out.println(person);
    29     }
    30     
    31     @Test
    32     public void update(){
    33         Person person=personDao.get(37);
    34         person.setAge(25);
    35         personDao.update(person);
    36     }
    37     
    38     @Test
    39     public void getAll(){
    40         List<Person> list=personDao.getAll();
    41         for (Person person : list) {
    42             System.out.println(person);
    43         }
    44     }
    45     
    46     @Test
    47     public void query(){
    48         QueryResult qr= personDao.query(2, 10);
    49         System.out.println("总记录数:"+qr.getCount());
    50         List<Person> list=qr.getList();
    51         for (Person person : list) {
    52             System.out.println(person);
    53         }
    54     }
    55     
    56     @Test
    57     public void delete(){
    58         personDao.delete(37);
    59     }
    60 }
    PersonTest.java
  • 相关阅读:
    springboot 项目部署到服务器
    Thymeleaf的注意项
    springboot定时器
    springboot
    随笔
    mysql数据库连接超过8小时失效的解决方案(springboot)
    Druid连接池与spring配置
    IDEA快捷键
    jsonp解决跨域,用div,css,js,jq实现textarea自适应高度
    mysql的查询、子查询及连接查询(商城查询常用)
  • 原文地址:https://www.cnblogs.com/caoyc/p/5594789.html
Copyright © 2011-2022 走看看