Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2314032
  • 博文数量: 252
  • 博客积分: 5472
  • 博客等级: 大校
  • 技术积分: 3107
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-17 18:39
文章分类

全部博文(252)

文章存档

2012年(96)

2011年(156)

分类: Java

2011-12-26 08:57:34

开发顺序
1 下载并安装Hibernate
2 Hibernate配置文件详解 配置与MySQL数据库的链接与映射文件User.hbm.xml
3 生成映射文件User.hbm.xml
4 编写持久化类User.java
5 编写辅助类HibernateSessionFactory.java 负责取得和关闭Hibernate的Session对象
6 编写DAO类UserDAO.java 编写根据用户名取得用户对象的getUser()
7 编写Service类UserService.java 编写valid()函数 调用UserDAO.java的getUser()函数执行函数验证
 
 
1 下载并安装Hibernate
下载hibernate-3.0.zip  将hibernate3.zip文件和lib下的所有文件都复制到新建的HibernateTest项目的lib子目录下
MySQL数据库的驱动文件复制到lib子目录下
 
2 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.           "">

  5. <!-- Generated by MyEclipse Hibernate Tools. -->
  6. <hibernate-configuration>

  7.     <session-factory>
  8.         <property name="myeclipse.connection.profile">
  9.             JDBC for MySQL
  10.         </property>
  11.         <property name="connection.url">
  12.             jdbc:mysql://localhost:3306/demo
  13.         </property>
  14.         <property name="connection.username">root</property>
  15.         <property name="connection.password">root</property>
  16.         <property name="connection.driver_class">
  17.             org.gjt.mm.mysql.Driver
  18.         </property>
  19.         <property name="dialect">
  20.             org.hibernate.dialect.MySQLDialect
  21.         </property>
  22.         <mapping resource="com/demo/hibernate/beans/User.hbm.xml" />


  23.     </session-factory>

  24. </hibernate-configuration>

使用XML文件进行配置时 指定Java类与数据库表格的映射文件位置 XML配置文件的位置必须在CLASSPATH的设定中 Web程式的WEB-INF/classes中 我们使用下面的方式读入XML文件以配置Hibernate

  1. SessionFactory sf = new Configuration().configure().buildSessionFactory();

Configuration表示Java类与数据库表格映射的集合 用于之后建立SessionFactory 之后Configuration就不再起作用了 预设的XML文件名称是hibernate.cfg.xml你也可以指定文件的名称

压缩包Hibernate-3.0.zip压缩包的etc子目录下提供默认的Hibernate配置文件hibernate.cfg.xml 我们要在HibernateTest中使用XML的配置文件 因此请复制该文件到HibernateTest项目的src目录下  并添加MySQL的相关配置项 这样 HibernateTest就支持Hibernate了

3  编写映射文件 User.hbm.xml

Hibernate映射文件包含了对象/关系映射所需的元数据 元数据包含持久化类的声明和属性到数据库的映射

映射文件是XML格式的文件 它负责持久化类与数据库表之间的映射 其根目录是hibernate-mapping 并通过属性package指定类所在的包 每一个表使用一个class定义 那么表示类的名称 table表示关联的表明 通过property子元素来映射类的变量名与数据库表字段名之间的映射关系

在这个HibernateTest项目中 我们建立一个映射文件User.hbm.xml来映射到数据表user 映射的类名为User 所在的包为com.demo.hibernate.beans

 

  1. <?xml version="1.0" encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3.                             "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4.                             "" >

  5. <!-- DO NOT EDIT: This is a generated file that is synchronized -->
  6. <!-- by MyEclipse Hibernate tool integration. -->
  7. <!-- Created Tue Aug 14 18:57:22 CST 2007 -->
  8. <hibernate-mapping package="com.demo.hibernate.beans">

  9.     <class name="User" table="user">
  10.         <id name="id" column="ID" type="integer">
  11.             <generator class="native"/>
  12.         </id>

  13.         <property name="username" column="username" type="string" />
  14.         <property name="password" column="password" type="string" />
  15.         <property name="email" column="email" type="string" />
  16.     </class>
  17.     
  18. </hibernate-mapping>

4  编写持久化类User.java

持久化类是指其实例需要被Hibernate持久化到数据库中的类 持久化通常是与模型中的实体域类 一般都是一张数据表对应一个持久化类 不能认为所有的持久化类的实例都是持久的状态 一个实例的状态也可能是瞬时的或脱管的。

在HibernateTest示例程序中 包含了一个持久化类User.java 该类包含表User的4个字段对应的变量 这些变量都申明为private类型的

 

  1. package com.demo.hibernate.beans;

  2. public class User {
  3.     private java.lang.Integer id;

  4.     private java.lang.String username;

  5.     private java.lang.String password;

  6.     private java.lang.String email;

  7.     public java.lang.String getEmail() {
  8.         return email;
  9.     }

  10.     public void setEmail(java.lang.String email) {
  11.         this.email = email;
  12.     }

  13.     public java.lang.Integer getId() {
  14.         return id;
  15.     }

  16.     public void setId(java.lang.Integer id) {
  17.         this.id = id;
  18.     }

  19.     public java.lang.String getPassword() {
  20.         return password;
  21.     }

  22.     public void setPassword(java.lang.String password) {
  23.         this.password = password;
  24.     }

  25.     public java.lang.String getUsername() {
  26.         return username;
  27.     }

  28.     public void setUsername(java.lang.String username) {
  29.         this.username = username;
  30.     }

  31. }

 

5  编写辅助类 HibernateSessionFactory.java

Hibernate的Session 这是一个持久化管理器 通过它从数据库中存取User

首先我们要从SessionFactory中获取一个Session

 

  1. SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

通过对configure()的调用来转载hibernate.cfg.xml配置文件 并初始化成一个Configuration实例 在创建SessionFactory之前 可以访问Configuration来设置其他属性

SessionFactory应该设置成单例模式 这样才能在程序中容易地访问SessionFactory

程序代码如下

 

  1. package com.demo.hibernate.util;

  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.cfg.Configuration;

  5. /**
  6.  * Configures and provides access to Hibernate sessions, tied to the
  7.  * current thread of execution. Follows the Thread Local Session
  8.  * pattern, see {@link }.
  9.  */
  10. public class HibernateSessionFactory {

  11.     /**
  12.      * Location of hibernate.cfg.xml file.
  13.      * NOTICE: Location should be on the classpath as Hibernate uses
  14.      * #resourceAsStream style lookup for its configuration file. That
  15.      * is place the config file in a Java package - the default location
  16.      * is the default Java package.


  17.      * Examples:

  18.      * CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
  19.      * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".
  20.      */
  21.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

  22.     /** Holds a single instance of Session */
  23.     private static final ThreadLocal threadLocal = new ThreadLocal();

  24.     /** The single instance of hibernate configuration */
  25.     private static final Configuration cfg = new Configuration();

  26.     /** The single instance of hibernate SessionFactory */
  27.     private static org.hibernate.SessionFactory sessionFactory;

  28.     /**
  29.      * Returns the ThreadLocal Session instance. Lazy initialize
  30.      * the SessionFactory if needed.
  31.      *
  32.      * @return Session
  33.      * @throws HibernateException
  34.      */
  35.     public static Session currentSession() throws HibernateException {
  36.         Session session = (Session) threadLocal.get();

  37.         if (session == null) {
  38.             if (sessionFactory == null) {
  39.                 try {
  40.                     cfg.configure(CONFIG_FILE_LOCATION);
  41.                     sessionFactory = cfg.buildSessionFactory();
  42.                 }
  43.                 catch (Exception e) {
  44.                     System.err.println("%%%% Error Creating SessionFactory %%%%");
  45.                     e.printStackTrace();
  46.                 }
  47.             }
  48.             session = sessionFactory.openSession();
  49.             threadLocal.set(session);
  50.         }

  51.         return session;
  52.     }

  53.     /**
  54.      * Close the single hibernate session instance.
  55.      *
  56.      * @throws HibernateException
  57.      */
  58.     public static void closeSession() throws HibernateException {
  59.         Session session = (Session) threadLocal.get();
  60.         threadLocal.set(null);

  61.         if (session != null) {
  62.             session.close();
  63.         }
  64.     }

  65.     /**
  66.      * Default constructor.
  67.      */
  68.     private HibernateSessionFactory() {
  69.     }

  70. }

这个类不但在他的静态初始器中使用了SessionFactory 还使用了了一个ThreadLocal变量来保存Session作为当前工作线程

 

6  编写DAO类UserDAO.java

所谓的DAO层 就是数据访问接口 为了基于Hibernate的开发中将业务层与数据层分开 DAO层只负责处理调用Hibernate API实现CRUD操作 Service层面向用户负责调用DAO层的代码 这样做的好处是 数据层的代码不用关心业务服务 可以更好的实现移植

 

  1. package com.demo.hibernate.dao;

  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Query;
  4. import org.hibernate.Session;
  5. import org.hibernate.Transaction;

  6. import com.demo.hibernate.beans.User;
  7. import com.demo.hibernate.util.HibernateSessionFactory;

  8. public class UserDAO {

  9.     public User getUser(String username) throws HibernateException {
  10.         Session session = null;
  11.         Transaction tx = null;
  12.         User user = null;
  13.         try {
  14.             session = HibernateSessionFactory.currentSession();
  15.             tx = session.beginTransaction();
  16.             Query query = session.createQuery("from User where username=?");
  17.             query.setString(0, username.trim());
  18.             user = (User)query.uniqueResult();
  19.             query = null;
  20.             tx.commit ();
  21.         }catch(HibernateException e){
  22.             throw e;
  23.         }finally{
  24.             if (tx!=null) {
  25.                 tx.rollback();
  26.             }
  27.             HibernateSessionFactory.closeSession();
  28.         }
  29.         return user;
  30.     }
  31. }

 

该类实现了一个getUser()函数 根据用户名username查询一个用户对象 在该函数中使用HibernateSessionFactory取得Session对象 然后通过session执行事务 创建查询对象 返回查询的用户对象,操作Session的代码都是Hibernate提供的API

7  编写Service类并运行

Service类即服务层 就是面向用户服务 它定义的方法都是与实际的业务相关的

此例子中 定义一个Service类UserService 他有一个函数valid() 根据用户名和密码来判断用户是否存在 改函数调用DAO层的UserDAO类来取得一个用户对象 并比较该对象的密码与输入的密码是否相等 如果相等就返回true 否则返回false  然后编写一个main()入口函数 用户调用valid()函数来执行业务的调用 并输出返回的结果

 

  1. package com.demo.hibernate.service;

  2. import com.demo.hibernate.beans.User;
  3. import com.demo.hibernate.dao.UserDAO;

  4. public class UserService {
  5.     
  6.     public boolean valid(String username, String password) {
  7.         UserDAO test = new UserDAO();
  8.         User user = test.getUser("admin");
  9.         if(user.getPassword().equals(password)) {
  10.             return true;
  11.         } else {
  12.             return false;
  13.         }
  14.     }
  15.     
  16.     public static void main(String[] args) {
  17.         UserService service = new UserService();
  18.         boolean login = service.valid("admin", "admin");
  19.         System.out.println("验证结果:"+login);
  20.     }
  21. }

接下来 运行 UserService.java 运行方式 Java应用程序 即可运行main()函数

此处记住 还要添加日志属性文件 三个日志属性文件 复制到Hibernate的src子目录下即可

运行程序 出现错误

 

  1. Communication failure during handshake. Is there a server running on localhost:3306?

原因:

结果在Mysql.com的官方网站上看到这个解释,是因为新的Mysql的认证机制发生了一些变化造成的,解决方法如下

解决方法:

I'd to change the authentication method at the mysql server:
set password for @ = old_password('');

将红色那部分在cmd-mysql登录之后敲进去就解决了

假如你的用户名密码是root root 那么红色部分就是

set password for );

最后正确运行的输出信息

 

  1. INFO - Hibernate 3.0.5
  2. INFO - hibernate.properties not found
  3. INFO - using CGLIB reflection optimizer
  4. INFO - using JDK 1.4 java.sql.Timestamp handling
  5. INFO - configuring from resource: /hibernate.cfg.xml
  6. INFO - Configuration resource: /hibernate.cfg.xml
  7. INFO - Mapping resource: com/demo/hibernate/beans/User.hbm.xml
  8. INFO - Mapping class: com.demo.hibernate.beans.User -> user
  9. INFO - Configured SessionFactory: null
  10. INFO - processing extends queue
  11. INFO - processing collection mappings
  12. INFO - processing association property references
  13. INFO - processing foreign key constraints
  14. INFO - Using Hibernate built-in connection pool (not for production use!)
  15. INFO - Hibernate connection pool size: 20
  16. INFO - autocommit mode: false
  17. INFO - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/demo
  18. INFO - connection properties: {user=root, password=****}
  19. INFO - RDBMS: MySQL, version: 5.5.17
  20. INFO - JDBC driver: Mark Matthews' MySQL Driver, version: 2.0.4
  21. INFO - Using dialect: org.hibernate.dialect.MySQLDialect
  22. INFO - Using default transaction strategy (direct JDBC transactions)
  23. INFO - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
  24. INFO - Automatic flush during beforeCompletion(): disabled
  25. INFO - Automatic session close at end of transaction: disabled
  26. INFO - Scrollable result sets: enabled
  27. INFO - JDBC3 getGeneratedKeys(): disabled
  28. INFO - Connection release mode: null
  29. INFO - Maximum outer join fetch depth: 2
  30. INFO - Default batch fetch size: 1
  31. INFO - Generate SQL with comments: disabled
  32. INFO - Order SQL updates by primary key: disabled
  33. INFO - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
  34. INFO - Using ASTQueryTranslatorFactory
  35. INFO - Query language substitutions: {}
  36. INFO - Second-level cache: enabled
  37. INFO - Query cache: disabled
  38. INFO - Cache provider: org.hibernate.cache.EhCacheProvider
  39. INFO - Optimize cache for minimal puts: disabled
  40. INFO - Structured second-level cache entries: disabled
  41. INFO - Statistics: disabled
  42. INFO - Deleted entity synthetic identifier rollback: disabled
  43. INFO - Default entity-mode: pojo
  44. INFO - building session factory
  45. WARN - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/F:/eeeeeee/HibernateTest/WebRoot/WEB-INF/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
  46. INFO - Not binding factory to JNDI, no JNDI name configured
  47. INFO - Checking 0 named queries
  48. 验证结果:true

 

 

阅读(12904) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~