开发顺序
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配置文件
- <?xml version='1.0' encoding='UTF-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "">
- <!-- Generated by MyEclipse Hibernate Tools. -->
- <hibernate-configuration>
- <session-factory>
- <property name="myeclipse.connection.profile">
- JDBC for MySQL
- </property>
- <property name="connection.url">
- jdbc:mysql://localhost:3306/demo
- </property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <property name="connection.driver_class">
- org.gjt.mm.mysql.Driver
- </property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <mapping resource="com/demo/hibernate/beans/User.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
使用XML文件进行配置时 指定Java类与数据库表格的映射文件位置 XML配置文件的位置必须在CLASSPATH的设定中 Web程式的WEB-INF/classes中 我们使用下面的方式读入XML文件以配置Hibernate
- 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
- <?xml version="1.0" encoding='UTF-8'?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "" >
- <!-- DO NOT EDIT: This is a generated file that is synchronized -->
- <!-- by MyEclipse Hibernate tool integration. -->
- <!-- Created Tue Aug 14 18:57:22 CST 2007 -->
- <hibernate-mapping package="com.demo.hibernate.beans">
- <class name="User" table="user">
- <id name="id" column="ID" type="integer">
- <generator class="native"/>
- </id>
- <property name="username" column="username" type="string" />
- <property name="password" column="password" type="string" />
- <property name="email" column="email" type="string" />
- </class>
-
- </hibernate-mapping>
4 编写持久化类User.java
持久化类是指其实例需要被Hibernate持久化到数据库中的类 持久化通常是与模型中的实体域类 一般都是一张数据表对应一个持久化类 不能认为所有的持久化类的实例都是持久的状态 一个实例的状态也可能是瞬时的或脱管的。
在HibernateTest示例程序中 包含了一个持久化类User.java 该类包含表User的4个字段对应的变量 这些变量都申明为private类型的
- package com.demo.hibernate.beans;
- public class User {
- private java.lang.Integer id;
- private java.lang.String username;
- private java.lang.String password;
- private java.lang.String email;
- public java.lang.String getEmail() {
- return email;
- }
- public void setEmail(java.lang.String email) {
- this.email = email;
- }
- public java.lang.Integer getId() {
- return id;
- }
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
- public java.lang.String getPassword() {
- return password;
- }
- public void setPassword(java.lang.String password) {
- this.password = password;
- }
- public java.lang.String getUsername() {
- return username;
- }
- public void setUsername(java.lang.String username) {
- this.username = username;
- }
- }
5 编写辅助类 HibernateSessionFactory.java
Hibernate的Session 这是一个持久化管理器 通过它从数据库中存取User
首先我们要从SessionFactory中获取一个Session
- SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
通过对configure()的调用来转载hibernate.cfg.xml配置文件 并初始化成一个Configuration实例 在创建SessionFactory之前 可以访问Configuration来设置其他属性
SessionFactory应该设置成单例模式 这样才能在程序中容易地访问SessionFactory
程序代码如下
- package com.demo.hibernate.util;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.cfg.Configuration;
- /**
- * Configures and provides access to Hibernate sessions, tied to the
- * current thread of execution. Follows the Thread Local Session
- * pattern, see {@link }.
- */
- public class HibernateSessionFactory {
- /**
- * Location of hibernate.cfg.xml file.
- * NOTICE: Location should be on the classpath as Hibernate uses
- * #resourceAsStream style lookup for its configuration file. That
- * is place the config file in a Java package - the default location
- * is the default Java package.
- * Examples:
- *
CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
- * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".
- */
- private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
- /** Holds a single instance of Session */
- private static final ThreadLocal threadLocal = new ThreadLocal();
- /** The single instance of hibernate configuration */
- private static final Configuration cfg = new Configuration();
- /** The single instance of hibernate SessionFactory */
- private static org.hibernate.SessionFactory sessionFactory;
- /**
- * Returns the ThreadLocal Session instance. Lazy initialize
- * the
SessionFactory
if needed.
- *
- * @return Session
- * @throws HibernateException
- */
- public static Session currentSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- if (session == null) {
- if (sessionFactory == null) {
- try {
- cfg.configure(CONFIG_FILE_LOCATION);
- sessionFactory = cfg.buildSessionFactory();
- }
- catch (Exception e) {
- System.err.println("%%%% Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- session = sessionFactory.openSession();
- threadLocal.set(session);
- }
- return session;
- }
- /**
- * Close the single hibernate session instance.
- *
- * @throws HibernateException
- */
- public static void closeSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- threadLocal.set(null);
- if (session != null) {
- session.close();
- }
- }
- /**
- * Default constructor.
- */
- private HibernateSessionFactory() {
- }
- }
这个类不但在他的静态初始器中使用了SessionFactory 还使用了了一个ThreadLocal变量来保存Session作为当前工作线程
6 编写DAO类UserDAO.java
所谓的DAO层 就是数据访问接口 为了基于Hibernate的开发中将业务层与数据层分开 DAO层只负责处理调用Hibernate API实现CRUD操作 Service层面向用户负责调用DAO层的代码 这样做的好处是 数据层的代码不用关心业务服务 可以更好的实现移植
- package com.demo.hibernate.dao;
- import org.hibernate.HibernateException;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import com.demo.hibernate.beans.User;
- import com.demo.hibernate.util.HibernateSessionFactory;
- public class UserDAO {
- public User getUser(String username) throws HibernateException {
- Session session = null;
- Transaction tx = null;
- User user = null;
- try {
- session = HibernateSessionFactory.currentSession();
- tx = session.beginTransaction();
- Query query = session.createQuery("from User where username=?");
- query.setString(0, username.trim());
- user = (User)query.uniqueResult();
- query = null;
- tx.commit ();
- }catch(HibernateException e){
- throw e;
- }finally{
- if (tx!=null) {
- tx.rollback();
- }
- HibernateSessionFactory.closeSession();
- }
- return user;
- }
- }
该类实现了一个getUser()函数 根据用户名username查询一个用户对象 在该函数中使用HibernateSessionFactory取得Session对象 然后通过session执行事务 创建查询对象 返回查询的用户对象,操作Session的代码都是Hibernate提供的API
7 编写Service类并运行
Service类即服务层 就是面向用户服务 它定义的方法都是与实际的业务相关的
此例子中 定义一个Service类UserService 他有一个函数valid() 根据用户名和密码来判断用户是否存在 改函数调用DAO层的UserDAO类来取得一个用户对象 并比较该对象的密码与输入的密码是否相等 如果相等就返回true 否则返回false 然后编写一个main()入口函数 用户调用valid()函数来执行业务的调用 并输出返回的结果
- package com.demo.hibernate.service;
- import com.demo.hibernate.beans.User;
- import com.demo.hibernate.dao.UserDAO;
- public class UserService {
-
- public boolean valid(String username, String password) {
- UserDAO test = new UserDAO();
- User user = test.getUser("admin");
- if(user.getPassword().equals(password)) {
- return true;
- } else {
- return false;
- }
- }
-
- public static void main(String[] args) {
- UserService service = new UserService();
- boolean login = service.valid("admin", "admin");
- System.out.println("验证结果:"+login);
- }
- }
接下来 运行 UserService.java 运行方式 Java应用程序 即可运行main()函数
此处记住 还要添加日志属性文件 三个日志属性文件 复制到Hibernate的src子目录下即可
运行程序 出现错误
- 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 );
最后正确运行的输出信息
- INFO - Hibernate 3.0.5
- INFO - hibernate.properties not found
- INFO - using CGLIB reflection optimizer
- INFO - using JDK 1.4 java.sql.Timestamp handling
- INFO - configuring from resource: /hibernate.cfg.xml
- INFO - Configuration resource: /hibernate.cfg.xml
- INFO - Mapping resource: com/demo/hibernate/beans/User.hbm.xml
- INFO - Mapping class: com.demo.hibernate.beans.User -> user
- INFO - Configured SessionFactory: null
- INFO - processing extends queue
- INFO - processing collection mappings
- INFO - processing association property references
- INFO - processing foreign key constraints
- INFO - Using Hibernate built-in connection pool (not for production use!)
- INFO - Hibernate connection pool size: 20
- INFO - autocommit mode: false
- INFO - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/demo
- INFO - connection properties: {user=root, password=****}
- INFO - RDBMS: MySQL, version: 5.5.17
- INFO - JDBC driver: Mark Matthews' MySQL Driver, version: 2.0.4
- INFO - Using dialect: org.hibernate.dialect.MySQLDialect
- INFO - Using default transaction strategy (direct JDBC transactions)
- INFO - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
- INFO - Automatic flush during beforeCompletion(): disabled
- INFO - Automatic session close at end of transaction: disabled
- INFO - Scrollable result sets: enabled
- INFO - JDBC3 getGeneratedKeys(): disabled
- INFO - Connection release mode: null
- INFO - Maximum outer join fetch depth: 2
- INFO - Default batch fetch size: 1
- INFO - Generate SQL with comments: disabled
- INFO - Order SQL updates by primary key: disabled
- INFO - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
- INFO - Using ASTQueryTranslatorFactory
- INFO - Query language substitutions: {}
- INFO - Second-level cache: enabled
- INFO - Query cache: disabled
- INFO - Cache provider: org.hibernate.cache.EhCacheProvider
- INFO - Optimize cache for minimal puts: disabled
- INFO - Structured second-level cache entries: disabled
- INFO - Statistics: disabled
- INFO - Deleted entity synthetic identifier rollback: disabled
- INFO - Default entity-mode: pojo
- INFO - building session factory
- 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
- INFO - Not binding factory to JNDI, no JNDI name configured
- INFO - Checking 0 named queries
- 验证结果:true
阅读(12904) | 评论(0) | 转发(0) |