第五章 Spring3.0 、Hibernate3.3与Struts2的整合 基于Annotation

来源:互联网 发布:网络模式nat 编辑:程序博客网 时间:2024/05/24 22:45


Annotation的方式是通过注解的方式把Struts2中的Action、Dao层的实现类、Service层的实现类交由Spring管理,不需要在配置文件中进行配置。但为了方便,事务的管理依然使用的是Schema的方式。如果有需要,可以参照4.3.2中的方式,使用@Transactional对service层进行事务管理。


5.4.1前期工作


给工程加入Spring与Hihernate的功能,这个步骤也5.1.1的相同。

http://blog.csdn.net/p_3er/article/details/10526617


打开Spring的扫描功能。


配置数据源。


配置SessionFactory。由于我们的实体类也是基于Annotation的,所以SessionFactory的class是AnnotationSessionFactoryBean。


把数据表生成Annotation的形式管理映射的实体类。


配置Schema方式的事务管理。


web.xml的配置与5.2.1一样。

http://blog.csdn.net/p_3er/article/details/10526617


由于struts2的配置都由注解完成,所以我们不再需要struts.xml配置文件。


5.4.2完整的Spring配置文件


<?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.xsdhttp://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.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"><!-- 打开Spring的扫描功能 --><context:component-scan base-package="cn.framelife.ssh"></context:component-scan><!-- 数据源 --><bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName"value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property><property name="username" value="root"></property><property name="password" value="test"></property></bean><!-- 配置SessionFactory.如果实体映射是基于注解的话,使用AnnotationSessionFactoryBean --><bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><!-- 引入数据源 --><property name="dataSource"><ref bean="dataSource" /></property><!-- Hibernate的相关配置 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop></props></property><!-- 映射文件或者映射类的路径。这是通过MyEclipse中的工具把数据表生成实体类及映射的时候自动生成的。 --><property name="annotatedClasses"><list><value>cn.framelife.ssh.entity.User</value></list></property></bean><!-- 配置事务 --><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="get*" read-only="true"/><tx:method name="add*" rollback-for="Exception"/></tx:attributes></tx:advice><aop:config><aop:pointcut id="pointcut"expression="execution(* cn.framelife.ssh.service..*(..))" /><aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" /></aop:config></beans>



5.4.3*DaoImpl


@Repositorypublic class UserDaoImpl extends HibernateDaoSupport implements UserDao {/** * 给HibernateDaoSupport注入一个SessionFactory. * 如果是xml的话,是直接把sesionFactory注入就行了。而这里需要一个额外的setter方法。 */@Autowiredpublic void setMySessionFactory(SessionFactory sessionFactory){super.setSessionFactory(sessionFactory);}/** * 保存或更新对象 */public void saveOrUpdateUser(User user) {getHibernateTemplate().saveOrUpdate(user);}/** * 根据id删除一条记录 */public void deleteById(Integer id) {getHibernateTemplate().delete(this.findUserById(id));}/** * 根据id获取一个记录对象 */public User findUserById(Integer id) {return (User) getHibernateTemplate().get(User.class, id);}/** * 根据Hql语句,以及开始位置、最大多少条数进行分页查询 */public List<User> findUserByLimit(final String hql, final int start,final int limit) {@SuppressWarnings("unchecked")List<User> list = getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {Query query = session.createQuery(hql);query.setFirstResult(start);query.setMaxResults(limit);List list = query.list();return list;}});return list;}/** * 根据一个User对象查询与这个对象中的非空属性一致的数据 */public List<User> findUserByExample(User user) {return getHibernateTemplate().findByExample(user);}/** * 根据Hql语句查询多条记录对象 */public List<User> findUserByHql(String hql) {return getHibernateTemplate().find(hql);}}


5.4.4*ServiceImpl

@Servicepublic class UserServiceImpl implements UserService {@Autowired private UserDao userDao;public void addUser(User user) {userDao.saveOrUpdateUser(user);}}


5.4.5*Action

/** * prototype 设置一次请求一个action对象 * <package name="a" extends="struts-default" namespace="/user"><action name="add" class="userAction"><result name="success">/success.jsp</result></action></package> * @ParentPackage相当于package extends * @Namespace 相当于package namespace * @Results 相当于result结果集 */@Controller@Scope("prototype")@ParentPackage(value = "struts-default")@Namespace("/user")@Results({@Result(name="success",value="/success.jsp"),})public class UserAction {/* * 如果参数过多的话,应该使用struts2驱动模型 */private String username;private String password;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;}@Autowired private UserService userService;/** * 如果想执行这个方法。页面上调用 user/user.action. */public String execute(){User user = new User();user.setUsername(username);user.setPassword(password);userService.addUser(user);return "success";}/** * 如果执行的是这个方法。页面调用user/user!next.action */public String next(){System.out.println("aaaaaaaaaaa");return "success";}}