hibernate学习二(HelloWorld)

一、建立hibernate配置文件

  在工程Hibernate_01_HelloWorld下的src上建立hibernate.cfg.xml,打开hibernate-release-4.3.11.Final/documentation/manual/en-US/html_single/index.html(hibernate开发文档),在文档中搜索configuration,找到 hibernate.cfg.xml配置文件的模板,复制到自己的工程中;

  1.修改配置文件适用jdbc和mysql数据库

 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         <!-- Database connection settings -->
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">root</property>
15 
16         <!-- JDBC connection pool (use the built-in) -->
17 <!--         <property name="connection.pool_size">1</property> -->
18 
19         <!-- SQL dialect -->
20         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
21 
22         <!-- Enable Hibernate's automatic session context management -->
23 <!--         <property name="current_session_context_class">thread</property> -->
24 
25         <!-- Disable the second-level cache  -->
26         <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
27 
28         <!-- Echo all executed SQL to stdout -->
29         <property name="show_sql">true</property>
30 
31         <!-- Drop and re-create the database schema on startup -->
32         <property name="hbm2ddl.auto">update</property>
33 
34         <mapping resource="com/model/Student.hbm.xml"/>
35 
36     </session-factory>
37 
38 </hibernate-configuration>

  1. Database connection settings, 数据库连接的配置;

  2. SQL dialect, hibernate的方言选择,支持多种数据库语言,因我用的是MySQL数据库,所有适用 MySQLDialect,其他可以从文档里查;

  3. Echo all executed SQL to stdout, 是否显示sql语句;

  4. Drop and re-create the database schema on startup, hibernate启动时删除或者创建数据库结构的策略;

  5.Orm, pojo映射配置文件;

二、建立实体类

  在src目录下建立实体类包com.model,并创建实体类Student.java

 1 public class Student {
 2     private int id;
 3     private String name;
 4     private int age;
 5     public int getId() {
 6         return id;
 7     }
 8     public void setId(int id) {
 9         this.id = id;
10     }
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public int getAge() {
18         return age;
19     }
20     public void setAge(int age) {
21         this.age = age;
22     }
23 }

  建立student映射文件与student.java同意路径,Student.hbm.xml(建议从hibernate文档中查找)

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="org.hibernate.tutorial.domain">
7 [...]
8 </hibernate-mapping>

  修改Student.hbm.xml,适用student.java类与数据库student表的映射;

 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 <!-- 设置到对应实体类所在的路径 -->
 7 <hibernate-mapping package="com.model">
 8 <!-- name对应实体类的名字 -->
 9     <class name="Student">
10 <!--     属性id为设置主键,name的值对应实体类里id属性 -->
11         <id name="id"></id>
12 <!--    其他字段的映射 -->
13         <property name="name"></property>
14         <property name="age"></property>
15     </class>
16 </hibernate-mapping>

二、在Mysql数据库中创建student表

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

三、建立hibernate辅助类

  根据hibernate官方文档,最好适用hibernate util辅助类,在src目录下新建com.util包,并在下面建立HibernateUtil.java类(博主学习的时候,这个版本的文档里的util类有错误,下面的代码已经改正)

 1 package com.util;
 2 
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 5 import org.hibernate.cfg.Configuration;
 6 
 7 public class HibernateUtil {
 8 
 9     private static final SessionFactory sessionFactory = buildSessionFactory();
10 
11     private static SessionFactory buildSessionFactory() {
12         try {
13             // Create the SessionFactory from hibernate.cfg.xml
14             return new Configuration().configure().buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(new Configuration().configure().getProperties()).build());
15         }
16         catch (Throwable ex) {
17             // Make sure you log the exception, as it might be swallowed
18             System.err.println("Initial SessionFactory creation failed." + ex);
19             throw new ExceptionInInitializerError(ex);
20         }
21     }
22 
23     public static SessionFactory getSessionFactory() {
24         return sessionFactory;
25     }
26 
27 }

四、编写测试类

  建立测试类Main,代码如下:

 1 import org.hibernate.Session;
 2 import org.hibernate.SessionFactory;
 3 
 4 import com.model.Student;
 5 import com.util.HibernateUtil;
 6 
 7 public class Main {
 8     public static void main(String[] args) {
 9         //设置要插入的数据
10         Student s = new Student();
11         s.setId(1);
12         s.setName("233");
13         s.setAge(100);
14         //通过util类创建sessionFactory
15         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
16         Session session = sessionFactory.openSession();
17         //开启事务
18         session.beginTransaction();
19         //将student存入数据库
20         session.save(s);
21         session.getTransaction().commit();
22         //关闭资源
23         session.close();
24         sessionFactory.close();
25     }
26 }

  结果:

  

项目结构:

  

----------------------------------------------------------------------------------------------------

此文为个人学习记录,如有参考转载,请注明出处 黑白熊的博客 http://www.cnblogs.com/xiong233/

posted @ 2017-01-05 13:45  熊熊熊摸了一下你的头  阅读(190)  评论(0编辑  收藏  举报