閱讀921 返回首頁    go 阿裏雲 go 技術社區[雲棲]


第五章 Spring3.0 、Hibernate3.3與Struts2的整合 基於Annotation


Annotation的方式是通過注解的方式把Struts2中的Action、Dao層的實現類、Service層的實現類交由Spring管理,不需要在配置文件中進行配置。但為了方便,事務的管理依然使用的是Schema的方式。如果有需要,可以參照4.3.2中的方式,使用@Transactional對service層進行事務管理。


5.4.1前期工作


給工程加入Spring與Hihernate的功能,這個步驟也5.1.1的相同。

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


打開Spring的掃描功能。


配置數據源。


配置SessionFactory。由於我們的實體類也是基於Annotation的,所以SessionFactory的class是AnnotationSessionFactoryBean。


把數據表生成Annotation的形式管理映射的實體類。


配置Schema方式的事務管理。


web.xml的配置與5.2.1一樣。

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


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


5.4.2完整的Spring配置文件


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p"
	xmlns:context="https://www.springframework.org/schema/context"
	xmlns:aop="https://www.springframework.org/schema/aop"
	xmlns:tx="https://www.springframework.org/schema/tx"
	xsi:schemaLocation="https://www.springframework.org/schema/beans 
		https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		https://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context-3.0.xsd
        https://www.springframework.org/schema/aop 
        https://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		https://www.springframework.org/schema/tx 
		https://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!-- 打開Spring的掃描功能 -->
	<context:component-scan base-package="cn.framelife.ssh"></context:component-scan>
	
	<!-- 數據源 -->
	<bean 
		>
		<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 
		>
		<!-- 引入數據源 -->
		<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  
		>
		<property name="sessionFactory" ref="sessionFactory"></property>	
	</bean>
	
	<tx:advice  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 
			expression="execution(* cn.framelife.ssh.service..*(..))" />
		<aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" />
	</aop:config>
</beans>



5.4.3*DaoImpl


@Repository
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	
	/**
	 * 給HibernateDaoSupport注入一個SessionFactory.
	 * 如果是xml的話,是直接把sesionFactory注入就行了。而這裏需要一個額外的setter方法。
	 */
	@Autowired
	public 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

@Service
public 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" >
			<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";
	}
}






最後更新:2017-04-03 16:49:03

  上一篇:go 超級有用的git reset --hard和git revert命令
  下一篇:go Hi3531添加16GByte(128Gbit) NAND Flash支持