1、导入架包(最小架包,共11个)
antlr-2.7.5H3.jar asm.jar asm-attrs.jar cglib-2.1.jar commons-collections-2.1.1.jar commons-logging-1.0.4.jar
dom4j-1.5.2.jar ehcache-1.1.jar hibernate3.jar jta.jar log4j-1.2.9.jar
2、添加 hibernate.cfg.xml 配置文件
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.profile">mysql</property> <property name="connection.url">jdbc:mysql://localhost:3306/demo</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="user.hbm.xml"/> </session-factory> </hibernate-configuration>
上述xml创建一个sessionFactory,方言dialect指定了hibernate生成的特定SQL语句,配置此项,应用会参考方言。mapping标签加载映射文件。
3、编写持久化类(User.java)
package com.qh.hibernate.beans; public class User { private int id; private String username; private String password; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
hibernate使用POJOs,和javabean很像。说明hibernate通过get和set方法访问对象。
4、编写映射文件(user.hbm.xml)
<?xml version="1.0" encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.qh.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> <property name="password" column="password" type="string"></property> <property name="email" column="email" type="string"></property> </class> </hibernate-mapping>
此映射文件负责持久化类和数据库表之间的映射;id属性是唯一标识符;generator 元素指定标识符的生成策略,我们选择 native,它提供了取决于数据库方言的可移植性。property元素的name属性值为持久化类的属性。
5、编写辅助类 HibernateSessionFactory.java
package com.qh.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 http://hibernate.org/42.html}. */ 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.<br><br> * Examples: <br> * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code> */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; /** Holds a single instance of Session */ @SuppressWarnings("unchecked") 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 <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ @SuppressWarnings("unchecked") 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 */ @SuppressWarnings("unchecked") public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * Default constructor. */ private HibernateSessionFactory() { } }
它是持久化管理器,我们通过它来从数据库中存取User。
6、编写DAO类(UserDao.java)
package com.qh.hibernate.dao; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.qh.hibernate.beans.User; import com.qh.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; } }
Dao层只负责调用hibernate API实现CURD操作。service层面向用户调用DAO层地代码。
7、编写service类(UserService.java)
package com.qh.hibernate.service; import com.qh.hibernate.beans.User; import com.qh.hibernate.dao.UserDao; public class UserService { public boolean valid(String username,String password){ UserDao userDao=new UserDao(); User user=userDao.getUser("admin"); if(user.getPassword().equals(password)){ return true; }else{ return false; } } public static void main(String args[]){ UserService userService=new UserService(); System.out.println("验证结果为:"+userService.valid("admin", "123")); } }
它定义的方法和具体的应用相关。
8、运行UserService.java,控制台输出如下:
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: user.hbm.xml INFO - Mapping class: com.qh.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: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/demo INFO - connection properties: {user=root, password=****, profile=mysql} INFO - RDBMS: MySQL, version: 5.5.13 INFO - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.8 ( Revision: ${svn.Revision} ) 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 - JDBC batch size: 15 INFO - JDBC batch updates for versioned data: disabled INFO - Scrollable result sets: enabled INFO - JDBC3 getGeneratedKeys(): enabled 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:/D:/My%20Documents/eclipse%20workspace/hibernateTest/WebContent/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
注:从cnblogs搬家的。