Hibernate 入门示例

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

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

环境:

myelipse2015+Hibernate5.2+mysql

一、新建一个hibernate01的Java项目并导入jar包

  1、在hibernate01项目下添加一个lib文件夹,用于存储需要的jar包

  2、在lib下面添加hibernate需要的jar包,在下载的hibernate文件中,找到hibernate-release-5.2.0.Finallib equired,并将下面的所有文件拷贝到lib中

  

  3、将mysql的驱动包mysql-connector-java-5.1.39-bin.jar拷贝到lib下

  4、选中lib下面所有文件,点击右键->Build Path->Add to Build Path

  

  

二、在mysql中建立一个test数据库,数据库中建一个person表

1 CREATE TABLE `person` (
2   `Id` int(11) NOT NULL AUTO_INCREMENT,
3   `Name` varchar(20) DEFAULT NULL,
4   `Age` tinyint(4) DEFAULT NULL,
5   `Gender` varchar(20) DEFAULT NULL,
6   PRIMARY KEY (`Id`)
7 ) 

三、类型对象和映射

  1、新建一个com.mypro.domain包

  2、在com.mypro.domain包下建一个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     
39 }

  3、配置实体类和数据库中表和字段的映射,在该包下建一个Person.hbm.xml文件,内容如下:

 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>

  package:实体类所在的包

  <class>标签:name:需要映射实体类的类名;table:数据库中对于的表明

  <id>标签:为数据库中主键字段配置,其它非主键字段用property来配置。name:实体类中属性名称,column:数据库中列名,type:属性类型

  <generator>标签:自动增长

  <properyt>标签:配置field主键字段使用

四、配置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 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>

五、测试

  

 1 package com.mypro.domain;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 import org.junit.Test;
 8 
 9 public class App {
10 
11     private static SessionFactory sessionFactory;
12     static{
13         
14         //通过配置类加载hibernate.cfg.xml
15         Configuration config=new Configuration();
16         config.configure("hibernate.cfg.xml");
17         //获取SessionFactory对象
18         sessionFactory= config.buildSessionFactory();
19     }
20     
21     /**
22      * 添加Person对象到数据库中
23      * @return 返回自动增长ID
24      */
25     public int addPerson(){
26         Session session=null;
27         Transaction tran=null;
28         try{
29             //获取Session对象
30             session=sessionFactory.openSession();
31             //启用事务
32             tran=session.beginTransaction();
33             Person person=new Person();
34             person.setName("张三");
35             person.setAge(25);
36             person.setGender("男");
37             //将数据保存到数据库
38             session.save(person);
39             //提交事务
40             tran.commit();
41             return person.getId();
42         }catch(Exception e){
43             if(tran!=null){
44                 tran.rollback();
45             }
46             e.printStackTrace();
47             return 0;
48         }finally{
49             if(session!=null){
50                 session.close();
51             }
52         }
53     }
54     
55     /**
56      * 通过ID获取Person对象
57      * @param id 主键ID
58      * @return 返回Person对象
59      */
60     public Person getPeronById(int id){
61         Session session=null;
62         Transaction tran=null;
63         try{
64             session=sessionFactory.openSession();
65             //获取Person对象,该方法中第一个参数,是需要获取对象的类型
66             Person person= session.get(Person.class, id);
67             return person;
68         }catch(Exception e){
69             e.printStackTrace();
70             return null;
71         }finally{
72             if(session!=null){
73                 session.close();
74             }
75         }
76     }
77     
78     public static void main(String[] args) {
79         App a=new App();
80         int id= a.addPerson();
81         Person p=a.getPeronById(id);
82         System.out.println(p);
83     }
84 }

  

  控制台输出结果:

Hibernate: insert into person (name, Age, Gender) values (?, ?, ?)
Hibernate: select person0_.Id as Id1_0_0_, person0_.name as name2_0_0_, person0_.Age as Age3_0_0_, person0_.Gender as Gender4_0_0_ from person person0_ where person0_.Id=?
Person [id=1, name=张三, age=25, gender=男]
原文地址:https://www.cnblogs.com/caoyc/p/5593406.html