MyEclipse-10.0下Struts2.1+Spring3.0+Hibernate3.3整合过程
新建web project:
命名为SSH,做如下设置:
新建后的工程目录如下:
然后开始添加SSH框架,这里我按照struts-spring-hibernate顺序进行添加。
首先添加struts2.1支持:
做如下设置后点next。
选择jar包,至少选择下图中选择的两个:
然后添加Spring3.0支持,做如下设置:
然后是添加hibernate3.3。为了在添加hibernate时,可以自动在配置文件里加入数据库的连接信息而不用再去手动写,需要在添加hibernate前配置一下数据库连接。我用的是mysql5.5,在mysql中新建数据库ssh,然后新建两张表:
CREATE TABLE `user` ( `id` int(100) NOT NULL auto_increment, `username` varchar(500) NOT NULL, `password` varchar(500) NOT NULL, PRIMARY KEY (`id`) ); |
CREATE TABLE `_log` ( `id` int(100) NOT NULL auto_increment, `msg` varchar(500) NOT NULL, PRIMARY KEY (`id`) ); |
然后在MyEclipse里打开DB Browser视图,在视图下空白区右键新建一个数据库连接:
做如下设置:
接下来正式添加hibernate3.3:
在下面的设置上选择spring的配置文件,这样hibernate就交给spring进行管理:
至此,SSH框架添加完成。工程结构如下:
至此,整合完毕,接下来创建一个项目测试一下。
一、model层
新建两个实体类:User.java和Log.java,并生成相应的get、set方法,然后使用Annotation注解相应属性与数据库表中的字段的对应关系:
User.java
package com.ecs610.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User { private int id; private String userName; private String password; @Id @GeneratedValue 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; } }
Log.java
package com.ecs610.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="_log") public class Log { private int id; private String msg; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
二、 DAO 层
利用MyEclipse的反向工程功能创建DAO接口及实现(以创建UserDAO及UserDAOImpl为例,Log的使用在本文并未实现),在表上右键,反向工程:
会在com.ecs610.dao.impl下得到一个名为UserDAO.java的文件,并且该文件有错误提示,引入User,删除冗余代码,并将UserDAO.java的文件名rename为UserDAOImpl.java。然后在UserDAOImpl.java中提取出(extract)接口,将接口命名为UserDAO.java,并将UserDAO.java移动到com.ecs610.dao包下:
项目结构图如下:
UserDAO.java
package com.ecs610.dao; import java.util.List; import com.ecs610.model.User; public interface UserDAO { public abstract void save(User transientInstance); public abstract void delete(User persistentInstance); public abstract User findById(java.lang.Integer id); public abstract List findByUserName(Object userName); public abstract List findAll(); public abstract User merge(User detachedInstance); }
UserDAOImpl.java
package com.ecs610.dao.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.ecs610.dao.UserDAO; import com.ecs610.model.User; public class UserDAOImpl extends HibernateDaoSupport implements UserDAO { private static final Logger log = LoggerFactory.getLogger(UserDAOImpl.class); // property constants public static final String PASSWORD = "password"; public static final String USER_NAME = "userName"; protected void initDao() { // do nothing } public void save(User transientInstance) { log.debug("saving User instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(User persistentInstance) { log.debug("deleting User instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public User findById(java.lang.Integer id) { log.debug("getting User instance with id: " + id); try { User instance = (User) getHibernateTemplate().get( "com.ecs610.dao.impl.User", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding User instance with property: " + propertyName + ", value: " + value); try { String queryString = "from User as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByUserName(Object userName) { return findByProperty(USER_NAME, userName); } public List findAll() { log.debug("finding all User instances"); try { String queryString = "from User"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public User merge(User detachedInstance) { log.debug("merging User instance"); try { User result = (User) getHibernateTemplate().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } }
三、Service层
按照下图的结构新建Service层的类:
UserService是接口类,UserServiceImpl是对应的实现类。各类的内容如下:
UserService.java
package com.ecs610.service; import com.ecs610.model.User; public interface UserService { public abstract void add(User user); }
UserServiceImpl.java
package com.ecs610.service.impl; import com.ecs610.dao.UserDAO; import com.ecs610.model.User; import com.ecs610.service.UserService; public class UserServiceImpl implements UserService { private UserDAO userDAO; public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public void add(User user) { this.userDAO.save(user); } }
然后,修改applicationContext.xml文件,实现“注入”:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/ssh" /> <property name="username" value="root" /> <property name="password" value="hel610" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.ecs610.model.User</value> <value>com.ecs610.model.Log</value> </list> </property> </bean> <bean id="userDAO" class="com.ecs610.dao.impl.UserDAOImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="logDAO" class="com.ecs610.dao.impl.LogDAOImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="userService" class="com.ecs610.service.impl.UserServiceImpl"> <property name="userDAO" ref="userDAO" /> </bean> </beans>
关于“注入”的理解:
关于ref=”userDAO”的理解是在UserServiceImpl类中新建或者引用了名为userDAO的对象。在Spring下的含义是将id为userDAO的对象(bean)注入给了当前类(对象)。(上文的.xml文件中的下划线为横线的userDAO为同一个对象,即同一个bean)
“注入”:配置文件指定了当前bean新建了哪一个对象(指定了当前bean的名称)、该对象属于哪个类、该对象是否有set方法、引用了哪个bean等信息,这样是一种灵活的方式,通过不同的配置可以实现不同的功能(通过引用不同的bean)。
然后新建类UserServiceImpl的JUnit test类。首先新建一个和目录src同一级别的Source Folder,起名为test,用于存放测试类。然后在UserServiceImpl.java类上单击右键—>new—>other:
然后将UserServiceImplTest.java的内容修改为如下:
UserServiceImplTest.java
package com.ecs610.service.impl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ecs610.model.User; import com.ecs610.service.UserService; public class UserServiceImplTest { @Test public void testAdd() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService service = (UserServiceImpl)applicationContext.getBean("userService"); User u = new User(); u.setId(1); u.setUserName("zhangsan"); u.setPassword("admin"); service.add(u); } }
接下来进行测试,在UserServiceImplTest.java 文件内右键— >Run As — >JUnit Test :
运行状态和结果如下图: