• Hibernate的一个简单应用例子


      Hibernate是一个开源的ORM框架,顾名思义,它的核心思想即ORM(Object Relational Mapping,对象关系映射),可以通过对象来操作数据库中的信息,据说开发者一开始是不太熟悉数据库SQL语句的,这也造就了hibernate的强大之处,它不强求开发者熟悉SQL语句也可以操作数据库,hibernate可以自动生成SQL语句,自动执行。用hibernate可以让开发者完全使用面想对象思维来操作数据库,本文使用hibernate实现了简单的对一个person数据表的基本增删改查操作。

    核心配置文件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 <hibernate-configuration>
     6     <session-factory>
     7         <!-- 以下四行分别为:数据库驱动类、Drivermanager获取连接的参数URL、用户名、密码  -->
     8         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     9         <property name="connection.url">jdbc:mysql://127.0.0.1/web?characterEcoding=utf-8</property>
    10         <property name="connection.username">root</property>
    11         <property name="connection.password">123456</property>
    12         <!-- 设置方言,hibernate会根据数据库的类型相应生成SQL语句 -->
    13         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    14         
    15         <!-- 控制台显示生成的sql语句,默认为false -->
    16         <property name="show_sql">true</property>
    17         <!-- 映射配置源文件的位置 -->
    18         <mapping resource="demo/pojo/Person.hbm.xml"/>
    19     </session-factory>
    20     
    21 </hibernate-configuration>

      

    映射文件Person.hbm.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     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 <hibernate-mapping>
     6     <!-- name是实体类全名,table为数据表名 -->
     7     <class name="demo.pojo.Person" table="Person">
     8         <id name="id" column="id">
     9             <!-- 主键生成方式,native是让hibernate自动识别 -->
    10             <generator class="native"></generator>
    11         </id>
    12         <!-- 
    13         注意点:
    14         0.name值为实体类中属性名,column为数据表中字段名;
    15         1.当实体类中属性名与对应数据表字段名相同时,后面的column可以省略,hibernate会自动匹配,例如下面age ;
    16         2.反之当实体类中属性名与对应数据表字段名不相同时,两项都要写上,例如下面gender和sex
    17         -->
    18         <property name="name" column="name"></property>
    19         <property name="gender" column="sex"></property>
    20         <property name="age"></property>
    21     </class>
    22 </hibernate-mapping>

    Session工厂类

     1 package demo.util;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 import org.hibernate.cfg.Configuration;
     6 import org.hibernate.service.ServiceRegistry;
     7 import org.hibernate.service.ServiceRegistryBuilder;
     8 
     9 public class HibernateSessionFactory {
    10     private static SessionFactory factory;
    11     private static ThreadLocal<Session> thread = new ThreadLocal<Session>();
    12     private static String path = "hibernate.cfg.xml";
    13     private static Configuration config = new Configuration();
    14     static {
    15         config.configure(path);
    16         ServiceRegistry service = new ServiceRegistryBuilder()//定义一个服务注册机
    17             .applySettings(config.getProperties()).buildServiceRegistry();
    18         factory = config.buildSessionFactory(service);//创建Session工厂类
    19     }
    20     
    21     public static Session getSession() {
    22         Session session = thread.get();
    23         if(session == null || !session.isOpen()) {
    24             session = factory.openSession();
    25             thread.set(session);
    26         }
    27         return session;
    28     }
    29     
    30     public static void closeSession() {
    31         Session session = thread.get();
    32         if(session != null && session.isOpen()) {
    33             session.close();
    34             thread.set(null);
    35         }
    36     }
    37     
    38 }

    DAO层封装数据各项操作的方法

     1 package demo.dao;
     2 
     3 import java.io.Serializable;
     4 import org.hibernate.Session;
     5 import org.hibernate.Transaction;
     6 import demo.pojo.Person;
     7 import demo.util.HibernateSessionFactory;
     8 
     9 public class PersonDaoImpl {
    10     //增删改查,此处以增为例
    11     public boolean add(Person p) {
    12         Session session = HibernateSessionFactory.getSession();//创建Session
    13         Transaction trans = session.beginTransaction();//开启事务
    14         try {
    15             Serializable id = session.save(p);//添加记录并获取主键值
    16             System.out.println(id+"为获取的主键值");//控制台查看主键值
    17             trans.commit();//提交事务
    18             return true;
    19         } catch (Exception e) {
    20             trans.rollback();//获取异常,则事务回滚
    21         } finally {
    22             HibernateSessionFactory.closeSession();//关闭Session
    23         }
    24         return false;
    25     }
    26 }

    测试类TestPerson

     1 package demo.test;
     2 
     3 import org.junit.Test;
     4 import demo.dao.PersonDaoImpl;
     5 import demo.pojo.Person;
     6 
     7 public class TestPerson {
     8     @Test
     9     public void testAdd() {
    10         //创建一个人类对象
    11         Person p = new Person();
    12         p.setName("张三");
    13         p.setGender("男");
    14         p.setAge(18);
    15         //创建dao层类对象并调用添加方法
    16         PersonDaoImpl dao = new PersonDaoImpl();
    17         dao.add(p);
    18     }
    19 }

    转自:http://www.cnblogs.com/young-z/p/7163645.html

  • 相关阅读:
    fork 入门
    java 注解 @Retention @interface 元数据
    JAVA泛型简析
    http数据流 gzip解压方法分析
    gdb调试提示 Missing separate debuginfos
    Vue2.x响应式原理
    观察者模式
    优秀博客收集
    切换npm源的方式
    前端模块化之ES Module
  • 原文地址:https://www.cnblogs.com/pretty-sunshine/p/7185297.html
Copyright © 2020-2023  润新知