在上一次Struts的基础上,整合Hibernate,依然参考网上大神的案例代码,由于版本问题的地方做了修改。
Eclipse+Struts地址->点这里
在此基础上,需要用到的相关的版本信息(有需要的可以留言^.^):
Hibernate :hibernate-release-4.3.10.Final
MySQL : MySQL Server 5.5
JDBC: mysql-connector-java-5.1.26-bin.jar
建议:大家在用的时候 包名最好改成自己的 这样在修改的过程中,可以更好的将映射的流程弄明白!
这里的步骤借鉴了原文的讲述,十分详细,感性探路的大神。
1.将Hibernate内的lib/required下的jar包和lib/jpa下的jar包复制到SSHProject项目的lib目录下。
2.在上面Struts项目的基础上添加com.tiny.ssh.dao和com.tiny.ssh.daoImpl包。分别创建BaseDao接口和UserDao类。
整理结构图(注意相应文件的位置和名字):
3.在数据库中创建对应的表user来写入要注册的用户。
create table user( userId int auto_increment, userName varchar(16) not null, password varchar(16) not null, gender int not null, primary key(userId) );
4.创建user表的Hibernate映射文件。因为这里要创建user表对应的POJO类,所以我这里把之前com.tiny.ssh.beans包改成com.tiny.ssh.forms包,用来存放页面传过来的表单数据,新创建com.tiny.ssh.beans包,用来创建POJO对象来对应数据库中的表。路径:POJO类同目录。
User.java:
package com.tiny.ssh.beans; public class User { private int userId; private String username; private String password; private int gender; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } 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 int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } }
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.tiny.ssh.beans"> <class name="User" table="user"> <id name="userId" column="userId"> <generator class="native"></generator> </id> <property name="username" column="userName" type="java.lang.String" not-null="true" length="16"></property> <property name="password" column="password" type="java.lang.String" not-null="true" length="16" /> <property name="gender" column="gender" type="java.lang.Integer" length="1" /> </class> </hibernate-mapping>
5.建立Hibernate配置文件。路径:src目录下。
Hibernate.cfg.xml(需要更改自己的数据库连接和最下面的映射):
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/ssh</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> --> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!-- <property name="hbm2ddl.auto">update</property> --> <mapping resource="com/tiny/ssh/beans/User.hbm.xml"/> </session-factory> </hibernate-configuration>
6.编写Session工厂类。整合Spring后,数据源的创建和SessionFactory的创建都交给Spring去管理,就无需这个工厂类了,所以这里我临时创建在daoImpl包里面。
HibernateSessionFactory.java(有几个方法已经不再使用了,这里作为演示,不再去修改):
package com.tiny.ssh.daoImpl; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateSessionFactory { private static final String CFG_FILE_LOCATION = "/Hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static final Configuration cfg = new Configuration() .configure(CFG_FILE_LOCATION); private static ServiceRegistryBuilder builder = new ServiceRegistryBuilder() .applySettings(cfg.getProperties()); private static ServiceRegistry registry; private static SessionFactory sessionFactory; public static Session currentSession() throws HibernateException { Session session = threadLocal.get(); if (session == null || session.isOpen() == false) { if (sessionFactory == null) { try { registry = builder.buildServiceRegistry(); sessionFactory = cfg.buildSessionFactory(registry); } catch (Exception e) { e.printStackTrace(); } } session = sessionFactory.openSession(); threadLocal.set(session); } return session; } public static void closeSession() throws HibernateException { Session session = threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } }
7.修改业务逻辑实现类。
UserManagerImpl.java:
package com.tiny.ssh.serviceImp; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import com.tiny.ssh.beans.User; import com.tiny.ssh.dao.BaseDao; import com.tiny.ssh.daoImpl.HibernateSessionFactory; import com.tiny.ssh.daoImpl.UserDao; import com.tiny.ssh.forms.UserForm; import com.tiny.ssh.service.UserManager; public class UserManagerImpl implements UserManager { private BaseDao dao; private Session session; public UserManagerImpl() { dao = new UserDao(); } @Override public void regUser(UserForm userForm) throws HibernateException { session = HibernateSessionFactory.currentSession(); dao.setSession(session); // 获取事务 Transaction ts = session.beginTransaction(); // 构造User对象 User user = new User(); user.setUsername(userForm.getUsername()); user.setPassword(userForm.getPassword()); user.setGender(userForm.getGender()); // 保存User对象 dao.saveObject(user); // 提交事务 ts.commit(); // 关闭Session HibernateSessionFactory.closeSession(); } }
运行的结果图(一定要注意对应地方的名称):
希望大家多多理解相应的映射~~