spring 3和mybatis 3集成并用junit4进行测试Word文档下载推荐.docx
- 文档编号:17256126
- 上传时间:2022-11-29
- 格式:DOCX
- 页数:11
- 大小:82.26KB
spring 3和mybatis 3集成并用junit4进行测试Word文档下载推荐.docx
《spring 3和mybatis 3集成并用junit4进行测试Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《spring 3和mybatis 3集成并用junit4进行测试Word文档下载推荐.docx(11页珍藏版)》请在冰豆网上搜索。
usetest;
5、mysql>
grantallprivilegesontest.*to
test@'
localhost'
identifiedby'
test'
;
6、mysql>
flushprivileges;
4、mysql>
createtableaccount_bak(account_idintnotnullauto_increment,
usernamevarchar(20),
passwordvarchar(20),
create_timedatetime,
primarykey(account_id));
二、spring和mybatis整合
1、在eclipse中创建一个javaproject,目录结构如下:
这是一个标准的maven工程的目录结构,下面逐一介绍上图涉及到的文件。
2、创建mybatis的配置文件mybatis.xml
<
?
xmlversion="
1.0"
encoding="
UTF-8"
?
>
!
DOCTYPEconfigurationPUBLIC"
-//mybatis.org//DTDConfig3.0//EN"
"
//mybatis.org/dtd/mybatis-3-config.dtd"
configuration>
/configuration>
上面的配置文件中,可以加入一些公共、常用的MyBatis方面的全局配置。
如handler、objectFactory、plugin、以及mappers的映射路径(由于在spring配置文件spring.xml中的SqlSessionFactoryBean有配置mapper的location,这里就不需要配置)等。
这个文件名称和下面的spring.xml中的configLocation中的值对应,不是随便写的。
3、创建spring的配置文件spring.xml
beansxmlns="
//www.springframework.org/schema/beans"
xmlns:
xsi="
//www.w3.org/2001/XMLSchema-instance"
xmlns:
p="
//www.springframework.org/schema/p"
context="
//www.springframework.org/schema/context"
jee="
//www.springframework.org/schema/jee"
tx="
//www.springframework.org/schema/tx"
xsi:
schemaLocation="
//www.springframework.org/schema/beans
//www.springframework.org/schema/beans/spring-beans-2.5.xsd
//www.springframework.org/schema/context
//www.springframework.org/schema/context/spring-context-2.5.xsd
//www.springframework.org/schema/jee
//www.springframework.org/schema/jee/spring-jee-2.5.xsd
//www.springframework.org/schema/tx
//www.springframework.org/schema/tx/spring-tx-2.5.xsd"
bean
class="
org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
/>
beanid="
dataSource"
org.springframework.jdbc.datasource.DriverManagerDataSource"
propertyname="
driverClassName"
value="
com.mysql.jdbc.Driver"
url"
jdbc:
mysql:
//localhost:
3306/test?
useUnicode=true&
amp;
characterEncoding=UTF-8"
username"
test"
password"
/bean>
--配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了-->
transactionManager"
org.springframework.jdbc.datasource.DataSourceTransactionManager"
ref="
tx:
annotation-driventransaction-manager="
--myBatis文件-->
sqlSessionFactory"
class="
org.mybatis.spring.SqlSessionFactoryBean"
configLocation"
classpath:
mybatis.xml"
mapperLocations"
value="
classpath*:
com/glen/model/*.xml"
accountDao"
com.glen.dao.AccountDao"
sessionFactory"
/>
accountService"
com.glen.service.AccountService"
context:
annotation-config/>
component-scanbase-package="
com.glen"
/beans>
4、JavaBean(Model、Entity)相关类、及mybatis的mapper对象
javabean:
packagecom.glen.model;
importjava.io.Serializable;
importjava.util.Date;
publicclassAccountimplementsSerializable{
privatestaticfinallongserialVersionUID=-7970848646314840509L;
privateIntegeraccountId;
privateStringusername;
privateStringpassword;
privateDatecreateTime;
publicAccount(){
super();
}
//下面是getter、setters
account-resultMap.xml
DOCTYPEmapperPUBLIC"
-//mybatis.org//DTDMapper3.0//EN"
//mybatis.org/dtd/mybatis-3-mapper.dtd"
mappernamespace="
accountMap"
<
resultMaptype="
com.hoo.entity.Account"
id="
accountResultMap"
idproperty="
accountId"
column="
account_id"
resultproperty="
createTime"
create_time"
/resultMap>
/mapper>
account-mapper.xml
"
account"
selectid="
getList"
parameterType="
com.glen.model.Account"
resultType="
list"
resultMap="
select*fromaccountwhereusernamelike'
%'
#{username}'
/select>
getAllAccount"
select*fromaccount
--accountResultMap是account-resultmap.xml中定义的resultmap-->
get"
[CDATA[
select*fromaccountwhereaccount_id=#{accountId}
]]>
--自动生成id策略-->
insertid="
add"
useGeneratedKeys="
true"
keyProperty="
insertintoaccount(account_id,username,password)
values(#{accountId,jdbcType=BIGINT},#{username},#{password})
--将最后插入的逐渐返回到java对象-->
selectKeyresultType="
int"
SELECTLAST_INSERT_ID()
/selectKey>
/insert>
updateid="
edit"
updateaccountset
username=#{username},
password=#{password}
whereaccount_id=#{accountId}
/update>
deleteid="
remove"
deletefromaccountwhereaccount_id=#{accountId}
/delete>
5、创建dao:
packagecom.glen.dao;
importjavax.annotation.Resource;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.springframework.stereotype.Repository;
importcom.glen.model.Account;
publicclassAccountDao{
privateSqlSessionFactorysessionFactory;
publicAccountDao(){
publicSqlSessionFactorygetSessionFactory(){
returnsessionFactory;
publicvoidsetSessionFactory(SqlSessionFactorysessionFactory){
this.sessionFactory=sessionFactory;
publicvoidinsert(Accountaccount){
SqlSessionsession=sessionFactory.openSession();
session.insert("
account.add"
account);
publicAccountgetAccountById(Accountaccount){
AccountaccountFromDb=(Account)session.selectOne("
account.get"
returnaccountFromDb;
6、创建service:
packagecom.glen.service;
importorg.springframework.stereotype.Service;
importcom.glen.dao.AccountDao;
publicclassAccountService{
privateAccountDaoaccountDao;
/**
*新增一个帐户。
*@paramaccount
*/
publicvoidinsertAccount(Accountaccount){
accountDao.insert(account);
*根据帐户ID查找帐户信息
*@return
returnaccountDao.getAccountById(account);
publicAccountDaogetAccountDao(){
returnaccountDao;
publicvoidsetAccountDao(AccountDaoaccountDao){
this.accountDao=accountDao;
Ok,至此spring和mybatis就整合好了。
三、用junit进行单元测试
在src/test/java目录下,创建一个测试类:
TestAccountService:
importstaticorg.junit.Assert.assertEquals;
importstaticorg.junit.Assert.assertNotNull;
importorg.apache.log4j.Logger;
importorg.junit.Before;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
publicclassTestAccountService{
Loggerlogger=Logger.getLogger("
TestAccountService"
);
AccountServiceservice=null;
@Before
publicvoidinit(){
ApplicationContextaCtx=newFileSystemXmlApplicationContext(
spring.xml"
AccountServiceservice=(AccountService)aCtx
.getBean("
assertNotNull(service);
this.service=service;
@Test
publicvoidtestInsertAccount(){
//创建一个帐户
Accountaccount=newAccount();
//account.setAccountId
(1);
account.setUsername("
selina"
account.setPassword("
123456"
//将创建的帐户插入到数据库中
service.insertAccount(account);
logger.debug("
accountid:
+account.getAccountId());
//从数据库获取刚才插入的帐户
AccountaccountFromDb=service.getAccountById(account);
assertNotNull(accountFromDb);
assertEquals(account.getAccountId(),accountFromDb.getAccountId());
测试通过,显示如下界面:
四、使用spring的标记来注入对象
如上所述,我们在spring的配置文件spring.xml中,定义了两个业务模块相关的bean,accountDao和accountService,但是在实际项目中,这样的dao和service会非常多,如果每个都要这样定义,会造成配置文件的体积过大,可阅读性和可维护性都会变差。
那么如何对spring.xml进行瘦身呢?
有两种方案,第一种方案是分模块开发,对于模块内部的bean,写在对应模块内部的spring配置文件中,如:
spring-account.xml;
第二种方案,就是使用spring的标记。
下面我想说说的就是,用spring的标记:
@Service@Repository@Resource来实现对象的注入。
在上面这个例子基础上,做以下步骤的修改:
1、
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- spring 3和mybatis 3集成并用junit4进行测试 mybatis 集成 并用 junit4 进行 测试