小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

基于全注解方式的SSH基礎框架(自認為拿得出手,歡迎拍磚,歡迎繼續(xù)完善)

 IT技術武館 2012-04-04

這是我為新項目專門搭建的基于全注解方式的SSH基礎框架,雖然是老掉牙的的東西,自我感覺很良好,好東西不敢獨享,曬曬等拍磚。

概述:基于struts2.23 + spring2.5.6 + hibernate3.6.4 + hibernate-generic-dao1.0(除了spring,我整合的都是最新的GA包,hibernate-generic-dao是google項目庫中一個開源的basedao,我灰常喜歡,因為我找不到更好更適合我的)

 

項目代碼是基于eclipse3.6創(chuàng)建的,很簡單,大家直接導入則可運行。

 

1.包結構,源碼,測試用例,配置文件一目了然。每個功能模塊都在modules包下做開發(fā),配置文件統(tǒng)一在resource管理(基實也沒多少配置文件,都用注解嘛)。

 

 

 

2.無論閱讀哪個web項目代碼,我都是先從web.xml開始,項目有什么東西一清二楚。

我這里將log4j監(jiān)聽放在第一,我想他應該能夠從系統(tǒng)啟動開啟就能記錄我的所有日志(求認證)。第二個監(jiān)聽是proxool數據庫連接池,聽說很高效,所以果斷引入(引入步驟搞得復雜吧,我還重寫了監(jiān)聽。一切為了穩(wěn)定,也好擴展我某日喜歡加入動態(tài)切換數據源做準備。呵呵)。OpenSessionInView,我想如果你不喜歡可以摘掉,反正我很喜歡。Struts2指定了自定義的struts.xml文件位置,指定掃描注解的action路徑。最后是proxool的可視化圖形監(jiān)控,很棒。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www./2001/XMLSchema-instance"
	xmlns="http://java./xml/ns/javaee" xmlns:web="http://java./xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java./xml/ns/javaee http://java./xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>framework</display-name>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/resources/log4j/log4j.properties</param-value>
	</context-param>
	<context-param>
		<param-name>propertyFile</param-name>
		<param-value>/WEB-INF/classes/resources/hibernate/proxool.properties</param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:resources/spring/applicationContext.xml</param-value>
	</context-param>
	<!-- log4j Listener -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- Proxool Listener -->
	<listener>
		<listener-class>org.chinasb.framework.core.db.ProxoolListener</listener-class>
	</listener>
	<!-- Open Session In View Filter -->
	<filter>
		<filter-name>OpenSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>OpenSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Spring Listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- Character Encoding Filter -->
	<filter>
        <filter-name>Set Character Encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <!-- 強制進行轉碼 -->
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Set Character Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
	<!-- 延長action中屬性的生命周期, -->
	<filter>
		<filter-name>struts-cleanup</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts-cleanup</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Struts2 Filter -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>struts-default.xml,struts-plugin.xml,resources/struts/struts.xml</param-value>
		</init-param>
        <init-param>
        	<param-name>actionPackages</param-name>
        	<param-value>org.chinasb.framework.modules</param-value>
        </init-param>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Proxool Monitoring -->
	<servlet>
		<servlet-name>Admin</servlet-name>
		<servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>Admin</servlet-name>
		<url-pattern>/admin.html</url-pattern>
	</servlet-mapping>
	<!-- Welcome List -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
3.applicationContext.xml,我想下面注釋得也比較清楚了,如果我寫錯了或理解錯了希望指正。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
	xmlns:xsi="http://www./2001/XMLSchema-instance"
	xmlns:context="http://www./schema/context"
	xsi:schemaLocation="

http://www./schema/beans

http://www./schema/beans/spring-beans.xsd

http://www./schema/context

http://www./schema/context/spring-context.xsd">

	<!-- 使用 annotation -->
	<context:annotation-config />

	<!-- 使用 annotation 自動注冊bean,并檢查@Controller, @Service, @Repository注解已被注入 -->
	<context:component-scan base-package="org.chinasb.framework.modules" />

	<!-- hibernate屬性配置 -->
	<context:property-placeholder location="classpath:resources/hibernate/hibernate.properties"/>

	<!-- Hibernate 配置管理 -->
	<import resource="applicationContext-persistence.xml" />

</beans>
4.hiberante配置所需的一些屬性,指定方言,開始hibernate緩存等,后面還有一個c3p0的數據連接池屬性。你們下載的代碼里面,數據源方面我換成了c3p0,因為proxool我配置的是隨web啟動的,而我又不想改成隨spring加載啟動。所以我開發(fā)中注釋掉proxool,以后上線再打開。
## hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.hbm2ddl.auto=update

## hibernate cache
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.cache.use_query_cache=false
hibernate.cache.use_second_level_cache=true

## C3P0 configuration
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/chinasb??useUnicode=true&characterEncoding=utf-8
hibernate.connection.username=root
hibernate.connection.password=root
5.applicationContext-persistence.xml,這里就是數據源及事務的一些配置了。事務我使用了cglib類級別的代理注解配置方式,如果你喜歡用jdk接口方式動態(tài)的代理,可以去掉 proxy-target-class="true"。順便也保留了聲名式事務。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
	xmlns:xsi="http://www./2001/XMLSchema-instance"
	xmlns:context="http://www./schema/context"
	xmlns:aop="http://www./schema/aop"
	xmlns:tx="http://www./schema/tx"
	xsi:schemaLocation="

http://www./schema/beans

http://www./schema/beans/spring-beans.xsd

http://www./schema/context

http://www./schema/context/spring-context.xsd

http://www./schema/aop

http://www./schema/aop/spring-aop.xsd

http://www./schema/tx

http://www./schema/tx/spring-tx.xsd">

	<!-- Proxool 數據源 -->
	<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>org.logicalcobwebs.proxool.ProxoolDriver</value>
		</property>
		<property name="url">
			<value>proxool.default</value>
		</property>
	</bean> -->

	<!-- C3P0 數據源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${hibernate.connection.driver_class}"/>
        <property name="jdbcUrl" value="${hibernate.connection.url}"/>
        <property name="properties">
            <props>
                <prop key="user">${hibernate.connection.username}</prop>
                <prop key="password">${hibernate.connection.password}</prop>
            </props>
        </property>
    </bean>

    <!-- SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="org.chinasb.framework.modules.*.model"/>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
				<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
				<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
			</props>
		</property>
	</bean>

	<!-- 配置事務管理 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 配置注解實現管理事務(cglib:proxy-target-class="true") -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

	<!-- 指定使用cglib -->
	<!-- <aop:aspectj-autoproxy proxy-target-class="true" />  -->

	<!-- 配置事務的傳播特性 -->
	<!--
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="batchUpdate" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	-->

	<!-- 配置事務的切入點 -->
	<!--
	<aop:config>
		<aop:pointcut id="targetMethod" expression="execution(* org.chinasb.framework.modules..service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="targetMethod" />
	</aop:config>
	-->

</beans>
6.struts.xml,你懂的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts./dtds/struts-2.0.dtd">

<struts>
    <!-- 開啟使用開發(fā)模式,詳細錯誤提示 -->
    <constant name="struts.devMode" value="false" />
    <!-- 將對象交給spring管理 -->
    <constant name="struts.objectFactory" value="spring" />
    <!-- 指定資源編碼類型 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
	<!-- 指定每次請求到達,重新加載資源文件 -->
    <constant name="struts.i18n.reload" value="false" />
    <!-- 指定每次配置文件更改后,自動重新加載 -->
    <constant name="struts.configuration.xml.reload" value="false" />
    <!-- 國際化資源文件 -->
    <constant name="struts.custom.i18n.resources" value="resources/content/Language" />
    <!-- 默認后綴名 -->
    <constant name="struts.action.extension" value="do,action,jhtml,," />
	<!-- Struts Annotation -->
    <constant name="actionPackages" value="org.chinasb.framework.modules"/>
</struts>

好了,下面我簡單講一下開發(fā)流程。

 

在modules下建立模塊,和相應的包(action,dao,model,service,util),比如我上面包結構的demo模塊。

 

demo.java,model類,映射數據庫中的表,每個model一張表,為了適應basedao,每個model還對應每個dao(不要覺得這是麻煩的)。jpa的注解,你們懂的,不解釋。

package org.chinasb.framework.modules.demo.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Demo implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String title;
    private String content;
    private Date publishdate;

    public int getId() {
	return id;
    }

    public void setId(int id) {
	this.id = id;
    }

    public String getTitle() {
	return title;
    }

    public void setTitle(String title) {
	this.title = title;
    }

    public String getContent() {
	return content;
    }

    public void setContent(String content) {
	this.content = content;
    }

    public Date getPublishdate() {
	return publishdate;
    }

    public void setPublishdate(Date publishdate) {
	this.publishdate = publishdate;
    }

}
DemoDao,接口類。我想在多數程序員的項目里做的絕大多數事情都是相關數據庫的CURD操作,所以基礎框架里整合一個強大的BaseDao是必須的,而我選擇了開源的GenericDao(覺得不適合你的可以替掉)。直接繼承GenericDao接口,指定操作的model,與主鍵的類型。
package org.chinasb.framework.modules.demo.dao;

import org.chinasb.framework.core.base.dao.hibernate.GenericDAO;
import org.chinasb.framework.modules.demo.model.Demo;

public interface DemoDao extends GenericDAO<Demo, Integer> {

}
DemoDaoImpl,呵,這樣寫我覺得不麻煩,不多說。@Repository注解交給spring管理。

package org.chinasb.framework.modules.demo.dao.impl;

import org.chinasb.framework.core.base.dao.BaseDAO;
import org.chinasb.framework.modules.demo.dao.DemoDao;
import org.chinasb.framework.modules.demo.model.Demo;
import org.springframework.stereotype.Repository;

@Repository
public class DemoDaoImpl extends BaseDAO<Demo, Integer> implements DemoDao {

}
BaseDAO,主要是注入sessionFactory給hibernate-generic-dao。
package org.chinasb.framework.core.base.dao;

import java.io.Serializable;

import org.chinasb.framework.core.base.dao.hibernate.GenericDAOImpl;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseDAO<T, ID extends Serializable> extends GenericDAOImpl<T, ID> {

    @Autowired
    @Override
    public void setSessionFactory(SessionFactory sessionFactory) {
	super.setSessionFactory(sessionFactory);
    }
}
DemoService,接下來就要定義一些相關數據庫操作的業(yè)務接口給上層使用了,這里主要列出了baseDao能操作的部分,像分頁,字段過濾查詢方面的沒有列出。
package org.chinasb.framework.modules.demo.service;

import java.util.List;
import org.chinasb.framework.modules.demo.model.Demo;

public interface DemoService {
    /**
     * 增加或更新demo
     *
     * @param demo
     * @return
     */
    public boolean save(Demo demo);

    /**
     * 批量增加或更新demo
     *
     * @param demo
     * @return
     */
    public boolean[] save(Demo[] demos);

    /**
     * 刪除demo
     *
     * @param demo
     * @return
     */
    public boolean remove(Demo demo);

    /**
     * 批量刪除demo
     *
     * @param demos
     */
    public void remove(Demo[] demos);

    /**
     * 根據主鍵刪除demo
     *
     * @param id
     * @return
     */
    public boolean removeById(Integer id);

    /**
     * 批量根據主鍵刪除demo
     *
     * @param ids
     */
    public void removeByIds(Integer[] ids);

    /**
     * 查詢demo數據記錄集
     *
     * @return
     */
    public List<Demo> findAll();

    /**
     * 根據主鍵查詢demo
     *
     * @param id
     * @return
     */
    public Demo findById(Integer id);

    /**
     * 批量根據主鍵查詢demo記錄集
     *
     * @param ids
     * @return
     */
    public Demo[] findByIds(Integer[] ids);

    /**
     * 持久化session數據到數據庫
     */
    public void flush();
}
DemoServiceImpl,接口實現。這里全用注解控制了事務,及演示如何使用baseDao。當然強大的baseDao并不僅僅這些方法,還有分頁等強大的查詢數據功能。大家可以在http://code.google.com/p/hibernate-generic-dao/ 進行查看。
package org.chinasb.framework.modules.demo.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.chinasb.framework.modules.demo.dao.DemoDao;
import org.chinasb.framework.modules.demo.model.Demo;
import org.chinasb.framework.modules.demo.service.DemoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DemoServiceImpl implements DemoService {
    @Resource
    private DemoDao demoDao;

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public boolean save(Demo demo) {
	return demoDao.save(demo);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public boolean[] save(Demo[] demos) {
	return demoDao.save(demos);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public boolean remove(Demo demo) {
	return demoDao.remove(demo);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void remove(Demo[] demos) {
	demoDao.remove(demos);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public boolean removeById(Integer id) {
	return demoDao.removeById(id);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void removeByIds(Integer[] ids) {
	demoDao.removeByIds(ids);
    }

    @Override
    public List<Demo> findAll() {
	return demoDao.findAll();
    }

    @Override
    public Demo findById(Integer id) {
	return demoDao.find(id);
    }

    @Override
    public Demo[] findByIds(Integer[] ids) {
	return demoDao.find(ids);
    }

    @Override
    public void flush() {
	demoDao.flush();
    }
}
DemoAction,這里演示了查看,增,刪功能。也是基于注解的方式,繼承了baseAction。
package org.chinasb.framework.modules.demo.action;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.chinasb.framework.core.base.action.BaseAction;
import org.chinasb.framework.modules.demo.model.Demo;
import org.chinasb.framework.modules.demo.service.DemoService;
import org.springframework.stereotype.Controller;

@Controller
public class DemoAction extends BaseAction {

    private static final long serialVersionUID = 1L;

    @Resource
    private DemoService demoService;

    @Action(value = "/demoAction", results = { @Result(name = SUCCESS, location = "/manager/modules/demo/index.jsp") })
    @Override
    public String execute() {
	List<Demo> demoList = demoService.findAll();
	httpServletRequest.setAttribute("DEMO_LIST", demoList);
	return SUCCESS;
    }

    @Action(value = "/demoAddAction", results = { @Result(name = SUCCESS, location = "/demoAction", type = "redirect") })
    public String add() {
	Demo demo = new Demo();
	demo.setTitle(httpServletRequest.getParameter("title"));
	demo.setContent(httpServletRequest.getParameter("content"));
	demo.setPublishdate(new Date());
	demoService.save(demo);
	return SUCCESS;
    }

    @Action(value = "/demoDeleteAction", results = { @Result(name = SUCCESS, location = "/demoAction", type = "redirect") })
    public String delete() {
	demoService.removeById(Integer.parseInt(httpServletRequest.getParameter("id")));
	return SUCCESS;
    }
}
 BaseAction,這里只封裝了基本的request,reponse,context,session,大家按需要繼續(xù)完善。
package org.chinasb.framework.core.base.action;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletContextAware,
	ServletResponseAware, ServletRequestAware, SessionAware {

    private static final long serialVersionUID = 1L;

    protected ServletContext servletContext;

    protected HttpServletRequest httpServletRequest;

    protected HttpServletResponse httpServletResponse;

    protected HttpSession httpSession;

    protected Map<String, Object> session;

    @Override
    public void setServletContext(ServletContext context) {
	this.servletContext = context;
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
	this.httpServletResponse = response;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
	this.httpServletRequest = request;
	this.httpSession = request.getSession();
    }

    @Override
    public void setSession(Map<String, Object> session) {
	this.session = session;
    }

}

最后就是測試用例了,這里使用了經典的junit4.4版本,依然是注解方式。

BaseTestTemplate,大家都不想每個用例都去寫一次讀取applicationContext吧,把一些公用的東西封裝起來吧。

package org.chinasb.framework.core.base.test;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:resources/spring/applicationContext.xml" })
@TransactionConfiguration(defaultRollback = false)
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class BaseTestTemplate {

}
DemoActionTest,簡單的測試用例,這里只是為了說明如何在這個框架里進行單元測試。所以我的目的達到了,簡單吧。
package org.chinasb.framework.modules.demo.action;

import java.util.Date;

import javax.annotation.Resource;

import org.chinasb.framework.core.base.test.BaseTestTemplate;
import org.chinasb.framework.modules.demo.model.Demo;
import org.chinasb.framework.modules.demo.service.DemoService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;

public class DemoActionTest extends BaseTestTemplate {

    @Resource
    private DemoService demoService;

    @Before
    public void setUp() throws Exception {
	System.out.println("測試開始");
    }

    @After
    public void tearDown() throws Exception {
	System.out.println("測試結束");
    }

    @BeforeTransaction
    public void beforeTransaction() {
	System.out.println("事務開始");
    }

    @AfterTransaction
    public void afterTransaction() {
	System.out.println("事務結束");
    }

    @Test
    public void testInsert() {
	Demo demo = new Demo();
	demo.setTitle("junit-test");
	demo.setContent("junit-content");
	demo.setPublishdate(new Date());
	demoService.save(demo);
    }

    @Test
    public void testInsertMore() {
	Demo[] demos = new Demo[10];
	for (int i = 0; i < 10; i++) {
	    Demo demo = new Demo();
	    demo.setTitle("junit-test" + i);
	    demo.setContent("junit-content" + i);
	    demo.setPublishdate(new Date());
	    demos[i] = demo;
	}
	demoService.save(demos);
    }
}

 


測試表:

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50150
Source Host           : localhost:3306
Source Database       : chinasb

Target Server Type    : MYSQL
Target Server Version : 50150
File Encoding         : 65001

Date: 2011-07-07 20:40:57
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `demo`
-- ----------------------------
DROP TABLE IF EXISTS `demo`;
CREATE TABLE `demo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(255) DEFAULT NULL,
  `publishdate` datetime DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=133 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of demo
-- ----------------------------
INSERT INTO demo VALUES ('131', 'test', '2011-07-06 01:29:19', 'test');
INSERT INTO demo VALUES ('132', 'test-2', '2011-07-07 20:40:38', 'test-2');

眾望所歸,出圖:

 

 

終于寫完了,好累啊。下一步跟汪兄商量如何完美整合他那個強大的數據級權限中間件(ralasafe),這樣在未來一投入使用即附帶有權限控制,多爽。好了,大家看得也累,喜歡的,不喜歡的都出來拍拍磚吧。不對的地方,請各位N人多多指正。

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯系方式、誘導購買等信息,謹防詐騙。如發(fā)現有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多