• hibernate的入门


    1. 什么是hibernate  

       ORM框架/持久层框架 jdbc的一个框架  

       ORM(Object Relational Mapping):对象关系映射。
       对象与关系型数据间之间的映射管理框架

       通过管理对象来改变数据库中的数据
       通过管理对象来操作数据库

      优势:跨数据库的无缝移植 

    2.如何使用hibernate

      2.1 添加hibernate相关依赖 

     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     3   <modelVersion>4.0.0</modelVersion>
     4   <groupId>com.yuan</groupId>
     5   <artifactId>T226_hibernate</artifactId>
     6   <packaging>war</packaging>
     7   <version>0.0.1-SNAPSHOT</version>
     8   <name>T226_hibernate Maven Webapp</name>
     9   <url>http://maven.apache.org</url>
    10   <properties>
    11         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    12         <maven.compiler.source>1.8</maven.compiler.source>
    13         <maven.compiler.target>1.8</maven.compiler.target>
    14         <junit.version>4.12</junit.version>
    15         <servlet.version>4.0.0</servlet.version>
    16         <hibernate.version>5.3.0.Final</hibernate.version>
    17         <mysql.driver.version>5.1.46</mysql.driver.version>
    18     </properties>
    19   <dependencies>
    20     
    21         <dependency>
    22             <groupId>junit</groupId>
    23             <artifactId>junit</artifactId>
    24             <version>${junit.version}</version>
    25             <scope>test</scope>
    26         </dependency>
    27 
    28         <dependency>
    29             <groupId>javax.servlet</groupId>
    30             <artifactId>javax.servlet-api</artifactId>
    31             <version>${servlet.version}</version>
    32             <scope>provided</scope>
    33         </dependency>
    34 
    35         <dependency>
    36             <groupId>org.hibernate</groupId>
    37             <artifactId>hibernate-core</artifactId>
    38             <version>${hibernate.version}</version>
    39         </dependency>
    40 
    41         <dependency>
    42             <groupId>mysql</groupId>
    43             <artifactId>mysql-connector-java</artifactId>
    44             <version>${mysql.driver.version}</version>
    45         </dependency>
    46   </dependencies>
    47   <build>
    48     <finalName>T226_hibernate</finalName>
    49     <plugins>
    50             <plugin>
    51                 <groupId>org.apache.maven.plugins</groupId>
    52                 <artifactId>maven-compiler-plugin</artifactId>
    53                 <version>3.7.0</version>
    54                 <configuration>
    55                     <source>${maven.compiler.source}</source>
    56                     <target>${maven.compiler.target}</target>
    57                     <encoding>${project.build.sourceEncoding}</encoding>
    58                 </configuration>
    59             </plugin>
    60         </plugins>
    61   </build>
    62 </project>

      2.2 在resource目录下添加hibernate.cfg.xml(核心配置文件) ,以及添加DTD支持

     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         <!-- 1. 数据库相关 -->
     8         <property name="connection.username">root</property>
     9         <property name="connection.password">***</property>
    10         <property name="connection.url">jdbc:mysql://localhost:3306/xm_sc?useUnicode=true&amp;characterEncoding=UTF-8
    11         </property>
    12         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    13         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    14 
    15         <!-- 配置本地事务(No CurrentSessionContext configured!) -->
    16         <property name="hibernate.current_session_context_class">thread</property>
    17 
    18         <!-- 2. 调试相关 -->
    19         <property name="show_sql">true</property>
    20         <property name="format_sql">true</property>
    21 
    22         <!-- 3. 添加实体映射文件 -->
    23         <mapping resource="com/yuan/one/entity/User.hbm.xml" />
    24       </session-factory>
    25     </hibernate-configuration>

      2.2.1 添加DTD支持

      添加到hibernate.cfg.xml(连接数据库信息)

    1 <!DOCTYPE hibernate-configuration PUBLIC
    2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    3     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


     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         <!-- 1. 数据库相关 -->
     8         <property name="connection.username">root</property>
     9         <property name="connection.password">***</property>//填入MySQL密码
    10         <property name="connection.url">jdbc:mysql://localhost:3306/xm_sc?useUnicode=true&amp;characterEncoding=UTF-8
    11         </property>                                           // 此处xm_sc改为MySQL数据库
    12         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    13         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    14 
    15         <!-- 配置本地事务(No CurrentSessionContext configured!) -->
    16         <property name="hibernate.current_session_context_class">thread</property>
    17 
    18         <!-- 2. 调试相关 -->
    19         <property name="show_sql">true</property>
    20         <property name="format_sql">true</property>
    21 
    22         <!-- 3. 添加实体映射文件 -->
    23         <mapping resource="com/yuan/one/entity/User.hbm.xml" />
    24       </session-factory>
    25     </hibernate-configuration>

      添加到User.hbm.xml(实体映射文件)

    1 <!DOCTYPE hibernate-mapping PUBLIC 
    2     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    3     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    实体类属性必须跟name值一样,后面的column必须跟数据库列段一致
     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     <!-- 
     7         class标签中:
     8             name:实体类的全路径
     9             table:实体类对应数据库中的表
    10         id标签:
    11             name:实体类中的属性(映射的是表的主键)
    12             type:属性对应的类型
    13             Column:属性对应的表中的哪一个列段
    14         property:
    15             name:实体类中的属性(映射的是表的非主键字段)
    16             type:属性对应的类型
    17             Column:属性对应的表中的哪一个列段
    18             
    19             List list = session.createQuery("from User").list();
    20           1、建模hibernate.cfg.xml对象,从中拿到了com/yuan/one/entity/User.hbm.xml
    21           2、建模了User.hbm.xml,拿到了com.yuan.one.entity.User 和 t_hibernate_User
    22           3、User user = Class.forName("com.yuan.con.entity.User").newInstance();
    23               Field userNameField = user.getClass("userName");
    24               Field userPwdField = user.getClass("userPwd");
    25               select user_name,user_pwd,real_name,....   得到数据库对象信息
    26               userNameField.set(user,源2);
    27               userPwdField.set(user,mima)
    28               ....
    29               最后user中的所有属性值都有了
    30           4、循环上一步操作,最终所有user实列都放入list集合中就是List  list
    31      -->
    32     <class name="com.yuan.one.entity.User" table="t_hibernate_User">
    33         <id name="id" type="java.lang.Integer" column="id">
    34             <generator class="increment" />
    35         </id>
    36         <property name="userName" type="java.lang.String" column="user_name">
    37         </property>
    38         <property name="userPwd" type="java.lang.String" column="user_pwd">
    39         </property>
    40         <property name="realName" type="java.lang.String" column="real_name">
    41         </property>
    42         <property name="sex" type="java.lang.String" column="sex">
    43         </property>
    44         <property name="birthday" type="java.sql.Date" column="birthday">
    45         </property>
    46         <property insert="false" update="false" name="createDatetime"
    47             type="java.sql.Timestamp" column="create_datetime">
    48         </property>
    49         <property name="remark" type="java.lang.String" column="remark">
    50         </property>
    51     </class>
    52 
    53 </hibernate-mapping>

      

       3、使用hibernate实现后台版增删改案列

       3.1 创建实体类,实体必须实现Serializable接口

     1 package com.yuan.one.entity;
     2 
     3 import java.io.Serializable;
     4 import java.sql.Date;
     5 import java.sql.Timestamp;
     6 
     7 public class User implements Serializable{
     8 
     9     private Integer id;
    10     private String userName;
    11     private String userPwd;
    12     private String realName;
    13     private String sex;
    14     private Date birthday;
    15     private Timestamp createDatetime;
    16     private String remark;
    17     public Integer getId() {
    18         return id;
    19     }
    20     public void setId(Integer id) {
    21         this.id = id;
    22     }
    23     public String getuserName() {
    24         return userName;
    25     }
    26     public void setuserName(String userName) {
    27         this.userName = userName;
    28     }
    29     public String getUserPwd() {
    30         return userPwd;
    31     }
    32     public void setUserPwd(String userPwd) {
    33         this.userPwd = userPwd;
    34     }
    35     public String getRealName() {
    36         return realName;
    37     }
    38     public void setRealName(String realName) {
    39         this.realName = realName;
    40     }
    41     public String getSex() {
    42         return sex;
    43     }
    44     public void setSex(String sex) {
    45         this.sex = sex;
    46     }
    47     public Date getBirthday() {
    48         return birthday;
    49     }
    50     public void setBirthday(Date birthday) {
    51         this.birthday = birthday;
    52     }
    53     public Timestamp getCreateDatetime() {
    54         return createDatetime;
    55     }
    56     public void setCreateDatetime(Timestamp createDatetime) {
    57         this.createDatetime = createDatetime;
    58     }
    59     public String getRemark() {
    60         return remark;
    61     }
    62     public void setRemark(String remark) {
    63         this.remark = remark;
    64     }
    65     @Override
    66     public String toString() {
    67         return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", realName=" + realName
    68                 + ", sex=" + sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + ", remark="
    69                 + remark + "]";
    70     }
    71     public User(String userName, String userPwd, String realName, String sex, Date birthday,
    72             Timestamp createDatetime, String remark) {
    73         super();
    74         this.userName = userName;
    75         this.userPwd = userPwd;
    76         this.realName = realName;
    77         this.sex = sex;
    78         this.birthday = birthday;
    79         this.createDatetime = createDatetime;
    80         this.remark = remark;
    81     }
    82     public User() {
    83         super();
    84         // TODO Auto-generated constructor stub
    85     }
    86     
    87     
    88 }

        数据库信息

    3.2、查询测试(QueryDemo)

     1 package com.yuan.one.test;
     2 
     3 import java.util.List;
     4 
     5 import org.hibernate.Session;
     6 import org.hibernate.SessionFactory;
     7 import org.hibernate.cfg.Configuration;
     8 
     9 /**
    10  * hibernate 中的查询案列
    11  * @author ly
    12  *
    13  */
    14 public class QueryDemo {
    15 
    16     public static void main(String[] args) {
    17         //对hibernate.cfg.xml进行建模拿到sessionfactory工厂
    18         Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
    19         SessionFactory SessionFactory = configuration.buildSessionFactory();
    20         //通过工厂模式获取到session会话(操作数据库)
    21         Session session = SessionFactory.openSession();
    22         //直接操作数据库
    23         List list = session.createQuery("from User").list();
    24         for (Object obj : list) {
    25             System.out.println(obj);
    26         }
    27         //关闭资源
    28         
    29         session.close();
    30     }
    31     
    32     
    33 }

         结果:(数据太大不便插图)

    Hibernate: 
        select
            user0_.id as id1_0_,
            user0_.user_name as user_nam2_0_,
            user0_.user_pwd as user_pwd3_0_,
            user0_.real_name as real_nam4_0_,
            user0_.sex as sex5_0_,
            user0_.birthday as birthday6_0_,
            user0_.create_datetime as create_d7_0_,
            user0_.remark as remark8_0_ 
        from
            t_hibernate_User user0_
    User [id=1, userName=rrr, userPwd=999, realName=null, sex=null, birthday=null, createDatetime=null, remark=null]
    User [id=2, userName=ls, userPwd=123, realName=李四, sex=男, birthday=2000-11-10, createDatetime=2018-09-29 09:58:13.0, remark=xyz]
    User [id=3, userName=zzz2, userPwd=123, realName=null, sex=null, birthday=2018-09-29, createDatetime=2018-09-29 10:07:20.0, remark=null]
    User [id=4, userName=zzz2, userPwd=123, realName=null, sex=null, birthday=2018-10-06, createDatetime=2018-10-06 07:17:54.0, remark=null]
    User [id=5, userName=bbbb, userPwd=123s, realName=null, sex=null, birthday=null, createDatetime=2018-10-16 16:12:53.0, remark=null]
    User [id=6, userName=ttttt, userPwd=6666, realName=null, sex=null, birthday=null, createDatetime=2018-10-17 11:46:20.0, remark=null]
    User [id=7, userName=吃吃吃, userPwd=mima, realName=null, sex=null, birthday=null, createDatetime=2018-10-17 15:01:55.0, remark=null]
    User [id=9, userName=吃吃吃22, userPwd=mima, realName=null, sex=null, birthday=null, createDatetime=2018-10-17 15:08:45.0, remark=null]
    User [id=11, userName=xxx, userPwd=123456, realName=xxx, sex=1, birthday=null, createDatetime=2018-11-17 09:47:03.0, remark=xxx]
    User [id=12, userName=xxx, userPwd=123456, realName=xxx, sex=1, birthday=null, createDatetime=2018-11-17 09:48:17.0, remark=xxx]
    User [id=13, userName=xxx, userPwd=123456, realName=xxx, sex=1, birthday=2018-11-17, createDatetime=2018-11-17 09:48:48.0, remark=xxx]
    User [id=14, userName=精华, userPwd=123456, realName=金燕, sex=女, birthday=null, createDatetime=2018-11-18 09:24:38.0, remark=开小差]

    3.3新增测试 (AddDemo)

     1 package com.yuan.one.test;
     2 
     3 import java.sql.Date;
     4 import java.sql.Timestamp;
     5 import java.util.List;
     6 
     7 import org.hibernate.Session;
     8 import org.hibernate.SessionFactory;
     9 import org.hibernate.Transaction;
    10 import org.hibernate.cfg.Configuration;
    11 
    12 import com.yuan.one.entity.User;
    13 
    14 /**
    15  * hibernate 增加案列
    16  * @author ly
    17  *
    18  */
    19 public class AddDemo {
    20 
    21     public static void main(String[] args) {
    22         //对hibernate.cfg.xml进行建模拿到sessionfactory工厂
    23         Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
    24         SessionFactory SessionFactory = configuration.buildSessionFactory();
    25         //通过工厂模式获取到session会话(操作数据库)
    26         Session session = SessionFactory.openSession();
    27         //获取事务对象
    28         Transaction transaction = session.beginTransaction();
    29         //直接操作数据库
    30         session.save(new User("yuan", "123456", "源", "男", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无介绍"));
    31         //提交事务
    32         transaction.commit();
    33         //关闭资源
    34         
    35         session.close();
    36     }
    37     
    38     
    39 }

    结果:(数据库显示)

    3.4修改测试(EditDemo)

     1 package com.yuan.one.test;
     2 
     3 import java.sql.Date;
     4 import java.sql.Timestamp;
     5 import java.util.List;
     6 
     7 import org.hibernate.Session;
     8 import org.hibernate.SessionFactory;
     9 import org.hibernate.Transaction;
    10 import org.hibernate.cfg.Configuration;
    11 
    12 import com.yuan.one.entity.User;
    13 
    14 /**
    15  * hibernate 修改案列
    16  * @author ly
    17 * 18 */ 19 public class EditDemo { 20 21 public static void main(String[] args) { 22 //对hibernate.cfg.xml进行建模拿到sessionfactory工厂 23 Configuration configuration = new Configuration().configure("/hibernate.cfg.xml"); 24 SessionFactory SessionFactory = configuration.buildSessionFactory(); 25 //通过工厂模式获取到session会话(操作数据库) 26 Session session = SessionFactory.openSession(); 27 //获取事务对象 28 Transaction transaction = session.beginTransaction(); 29 //直接操作数据库 30 //传统用法 31 // User user= new User("yuan2", "123456", "源2", "男", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无介绍2"); 32 // user.setId(15); 33 // session.update(user); 34 // session.save(); 35 //更改单个列段 36 User user = session.get(User.class, 15); 37 System.out.println(user); 38 user.setRealName("源3"); 39 //提交事务 40 transaction.commit(); 41 //关闭资源 42 43 session.close(); 44 } 45 46 47 }

     结果:(更改单个列段效果)

      3.5删除测试(DelDemo)

     1 package com.yuan.one.test;
     2 
     3 import java.sql.Date;
     4 import java.sql.Timestamp;
     5 import java.util.List;
     6 
     7 import org.hibernate.Session;
     8 import org.hibernate.SessionFactory;
     9 import org.hibernate.Transaction;
    10 import org.hibernate.cfg.Configuration;
    11 
    12 import com.yuan.one.entity.User;
    13 
    14 /**
    15  * hibernate 增加案列
    16  * @author ly
    17  *
    18  */
    19 public class DelDemo {
    20 
    21     public static void main(String[] args) {
    22         //对hibernate.cfg.xml进行建模拿到sessionfactory工厂
    23         Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
    24         SessionFactory SessionFactory = configuration.buildSessionFactory();
    25         //通过工厂模式获取到session会话(操作数据库)
    26         Session session = SessionFactory.openSession();
    27         //获取事务对象
    28         Transaction transaction = session.beginTransaction();
    29         //直接操作数据库
    30         User user=new User();
    31         user.setId(15);
    32         session.delete(user);
    33         //提交事务
    34         transaction.commit();
    35         //关闭资源
    36         
    37         session.close();
    38     }
    39     
    40     
    41 }

      结果:(根据id删除)

    谢谢观看  ^-^  !!!

  • 相关阅读:
    09 Django组件之用户认证组件
    二叉树的三种遍历(非递归)
    CoderForce 141C-Queue (贪心+构造)
    CoderForce 140C-New Year Snowmen(贪心)
    UVA-1663 Purifying Machine (最大匹配数)
    UVA-10801 Lift Hopping (最短路)
    UVA-1660 Cable TV Network (最小割)
    UVA-820 Internet Bandwidth (最大流)
    UVA-1336 Fixing the Great Wall(区间DP)
    棋盘分割(二维区间DP)
  • 原文地址:https://www.cnblogs.com/ly-0919/p/11291080.html
Copyright © 2020-2023  润新知