下面将介绍使用spring+mybatis的开发样例:
首先,笔者创建的是一个maven工程,在开发先先导入相关的依赖jar:
pom.xml:
junit
junit
4.11
test
org.springframework
spring-core
3.0.5.RELEASE
org.springframework
spring-context
3.0.5.RELEASE
org.springframework
spring-beans
3.0.5.RELEASE
org.springframework
spring-jdbc
3.0.5.RELEASE
org.springframework
spring-web
3.0.5.RELEASE
org.springframework
spring-webmvc
3.0.5.RELEASE
mysql
mysql-connector-java
5.1.13
org.slf4j
slf4j-api
1.7.2
org.slf4j
slf4j-log4j12
1.7.2
org.mybatis
mybatis-spring
1.2.1
org.mybatis
mybatis
3.2.1
javax.servlet
javax.servlet-api
3.1.0
provided
jstl
jstl
1.2
proxool
proxool
0.9.1
proxool
proxool-cglib
0.9.1
javax.servlet.jsp
jsp-api
2.2
provided
web.xml中对spring和数据库连接池的配置:
log4jConfigLocation
/WEB-INF/log4j.xml
log4jRefreshInterval
60000
org.springframework.web.util.Log4jConfigListener
contextConfigLocation
/WEB-INF/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
spring3
org.springframework.web.servlet.DispatcherServlet
2
spring3
/
ServletConfigurator
org.logicalcobwebs.proxool.configuration.ServletConfigurator
xmlFile
WEB-INF/proxool.xml
1
在这里要注意,因为我使用了数据库连接池proxool,虽然已经设置servlet的启动级别是1,但是由于在servlet启动之前,spring(ContextLoaderListener)监听器已启动了,所以在spring监听启动时它会报一个找不到对应的数据源的SQLException。对于这个问题,本可以通过更改spring为servlet启动,并将启动级别设置为proxool配置加载之后解决:
contextConfigLocation
org.springframework.web.context.ContextLoaderServlet
2
但是因为spring3以后就不支持使用servlet启动了,官方推荐使用listener启动applicationContext。所以这个方法在新版本不适合了,不过这个异常可以忽略,因为proxool在整个项目加载完成的时候的确以及完成了加载,所以在项目运行起来以后是不会报错的,开始报错是spring做的一个检查。
为了解决乱码问题最好在web.xml中加上这个配置:
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
characterEncodingFilter
/*
下面是对spring3-servlet.xml的配置,它里面申明的bean都存放在webApplicationContext中:
default-lazy-init="false" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd">
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
error
下面对applicationContext.xml进行配置(这里使用了两个数据源):
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
base-package="com.pinche.statistic.dao,
com.pinche.statistic.service" />
Application.java是下面会用到的一个实体bean:
public classApplication {public static final int APP_DISABLE = 0;public static final int APP_ENABLE = 1;privateInteger id;private String appAccount;//每个app对应一个账户标识;对应生成的数据表
privateString appName;privateString appICON;privateString appDesc;privateString appURL;privateDate createTime;private int isDisable;//'是否前台显示:0显示,1不显示'
}
首先我们要编写一个与mapper.xml文件映射的接口文件,mybatis会将这个接口文件和对应的mapper文件中的sql语句关联,自动实现这个接口文件。在之后的开发中我们直接调用这个接口文件就可以了,因为内存中已经有接口相对应的实例了。
ApplicationsMapper.xml文件:
/p>
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
INSERT INTO applications
(appName,appAccount,appICON,appDesc,appURL,createTime)
VALUES
(#{appName},#{appAccount},#{appICON},#{appDesc},#{appURL},#{createTime})
DELETE FROM applications WHERE
appAccount=#{appAccount}
UPDATE applications
appName=#{appName},
appICON=#{appICON},
appDesc=#{appDesc},
appURL=#{appURL},
isDisable=#{isDisable}
WHERE appAccount=#{appAccount}
select* from applications where appAccount =#{appAccount}
select*from applications
对ApplicationsMapper.xml文件的配置必须要注意的是它的命名空间是必须的,而且是对应接口文件的全名!并且每个sql语句的id属性和接口文件中的方法名一致!!
下面是ApplicationsMapper.java文件,也就是对应的接口文件:
packagecom.pinche.statistic.mapper;importjava.util.List;importcom.pinche.statistic.domain.Application;public interfaceApplicationsMapper {voidadd(Application app);voiddelete(String appAccount);voidupdate(Application app);
Application findByAppAccount(String appAccount);
ListfindAll();
}
通过以上的的配置,大家可以在test中测试一下自己的代码了
@Testpublic voidtestCreateTable() {
ApplicationContext aContext= new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");
ApplicationsMapper mapper= (ApplicationsMapper) aContext.getBean(ApplicationsMapper.class);
Application app= newApplication();
app.setAppAccount("androidApp");
mapper.add(app);
}
以上测试了add方法,其他的测试方法大家可以照着写一写。如果插入成功恭喜,你的环境已经搭好了。
接下来是将继续这个样例系统的Dao层,service层和controller层。
这个dao层吧,项目中就是这么用的,不过现在通过大家的指正,mybatis提供了@param来解决多参数问题,ok,这么看来这个Dao层的确不需要了。
packagecom.pinche.statistic.dao;importjava.util.List;importcom.pinche.statistic.domain.Application;public interfaceAppDao {booleanadd(Application app);booleandelete(String appAccount);booleanupdate(Application app);
Application findByAppAccount(String appAccount);
ListfindAll();
}
packagecom.pinche.statistic.dao.impl;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.dao.DataAccessException;importorg.springframework.stereotype.Repository;importcom.pinche.statistic.dao.AppDao;importcom.pinche.statistic.domain.Application;importcom.pinche.statistic.mapper.ApplicationsMapper;
@Repositorypublic class AppDaoImpl implementsAppDao {
@AutowiredprivateApplicationsMapper mapper;
@Overridepublic booleanadd(Application app) {try{
mapper.add(app);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@Overridepublic booleandelete(String appAccount) {try{
mapper.delete(appAccount);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@Overridepublic booleanupdate(Application app) {try{
mapper.update(app);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@OverridepublicApplication findByAppAccount(String appAccount) {try{
Application findByAppAccount=mapper.findByAppAccount(appAccount);returnfindByAppAccount;
}catch(DataAccessException e) {
e.printStackTrace();
}return null;
}
@Overridepublic ListfindAll() {try{returnmapper.findAll();
}catch(DataAccessException e) {
e.printStackTrace();
}return null;
}
}
自行设计的DAO层对象容器(在DAO对象很多时,如果在service层要调用对应的DAO还得手动注入,通过引用这个DAO层对象容器,可以实现在需要使用DAO时迅速找需要的DAO,省去了繁杂的手动注入,而且spring默认的bean都是单例的,无论在何处注入一个实体bean其实都是同一个。这样做更方便):
packagecom.pinche.statistic.dao;importjava.lang.reflect.Field;importjavax.annotation.PostConstruct;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Repository;
@Repositorypublic classBaseDAL {private static final Logger logger = LoggerFactory.getLogger(BaseDAL.class);
@AutowiredprivateAppDao _appDao;public staticAppDao appDao;
@AutowiredprivateMetaDataDao _metaDataDao;public staticMetaDataDao metaDataDao;
@AutowiredprivateDDLManager _DDLManager;public staticDDLManager DDLManager;
@AutowiredprivateAnalyzeDao _analyzeDao;public staticAnalyzeDao analyzeDao;
@AutowiredprivateDialstatisticsDao _dialstatisticsDao;public staticDialstatisticsDao dialstatisticsDao;
@PostConstructpublic voidinit() {long start =System.currentTimeMillis();
logger.debug("start init BaseDAL ...");try{
Field[] fields= this.getClass().getDeclaredFields();for (int i = 0; i < fields.length; i++) {
String fieldname=fields[i].getName();if (fieldname.startsWith("_")) {
String sfieldname= fieldname.substring(1);
Field sfield= this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseDAL OVER, consume = {}ms",
System.currentTimeMillis()-start);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(NoSuchFieldException e) {
e.printStackTrace();
}catch(SecurityException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
如果使用了以上的层管理容器,如果要在容器中添加一个DAO(例如:DemoDao),只需在这个容器中添加一个这样的声明:
@AutowiredprivateDemoDao _demoDao;public static DemoDao demoDao;
packagecom.pinche.statistic.service;importjava.util.List;importcom.pinche.statistic.domain.Application;/***@authorJACKWANG
*@sinceDec 23, 2013*/
public interfaceAppService {
Application find(String appAccount);booleanupdate(Application app);booleansetDisable(String appAccount);booleansetEnable(String appAccount);
ListfindAll();
}
packagecom.pinche.statistic.service.impl;importjava.util.List;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Service;importcom.pinche.statistic.dao.BaseDAL;importcom.pinche.statistic.domain.Application;importcom.pinche.statistic.service.AppService;importcom.pinche.statistic.utils.SystemUtils;/***@authorJACKWANG
*@sinceDec 23, 2013*/@Servicepublic class AppServiceImpl implementsAppService {private static final Logger logger =LoggerFactory
.getLogger(AppServiceImpl.class);
@OverridepublicApplication find(String appAccount) {returnBaseDAL.appDao.findByAppAccount(appAccount);
}
@Overridepublic booleanupdate(Application app) {
String appAccount=app.getAppAccount();if (appAccount == null && "".equals(appAccount)) {return true;
}returnBaseDAL.appDao.update(app);
}
@Overridepublic booleansetDisable(String appAccount) {
Application app= newApplication();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_DISABLE);returnBaseDAL.appDao.update(app);
}
@Overridepublic booleansetEnable(String appAccount) {
Application app= newApplication();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_ENABLE);returnBaseDAL.appDao.update(app);
}
@Overridepublic ListfindAll() {returnBaseDAL.appDao.findAll();
}
}
哈哈,使用层对象管理容器是不是很方便。通过一个引用就能获得所有的DAO支持。所以我在service层也构建了一个service层对象管理容器BaseBLL:
packagecom.pinche.statistic.service;importjava.lang.reflect.Field;importjavax.annotation.PostConstruct;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;/***@authorJACKWANG
*@sinceDec 23, 2013*/@Servicepublic classBaseBLL {private static final Logger logger = LoggerFactory.getLogger(BaseBLL.class);
@AutowiredprivateAnalyzeService _analyzeService;public staticAnalyzeService analyzeService;
@AutowiredprivateAppService _appService;public staticAppService appService;
@AutowiredprivateMetaDataService _metaDataService;public staticMetaDataService metaDataService;
@PostConstructpublic voidinit() {long start =System.currentTimeMillis();
logger.debug("start init BaseBLL ...");try{
Field[] fields= this.getClass().getDeclaredFields();for (int i = 0; i < fields.length; i++) {
String fieldname=fields[i].getName();if (fieldname.startsWith("_")) {
String sfieldname= fieldname.substring(1);
Field sfield= this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseBLL OVER, consume = {}ms",
System.currentTimeMillis()-start);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(NoSuchFieldException e) {
e.printStackTrace();
}catch(SecurityException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
好了下面应该是controller层的编写了,但是由于笔者以上的代码只是摘录了系统中的部分,而在controller中涉及到其他的内容,如果直接摘录可能和以上的代码衔接不上。所以这里就不进行了controller层的具体介绍了。本系统controller层使用的是SpringMVC,开发效率一级赞。
packagecom.pinche.statistic.dao;importjava.util.List;importcom.pinche.statistic.domain.Application;public interfaceAppDao {booleanadd(Application app);booleandelete(String appAccount);booleanupdate(Application app);
Application findByAppAccount(String appAccount);
ListfindAll();
}
packagecom.pinche.statistic.dao.impl;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.dao.DataAccessException;importorg.springframework.stereotype.Repository;importcom.pinche.statistic.dao.AppDao;importcom.pinche.statistic.domain.Application;importcom.pinche.statistic.mapper.ApplicationsMapper;
@Repositorypublic class AppDaoImpl implementsAppDao {
@AutowiredprivateApplicationsMapper mapper;
@Overridepublic booleanadd(Application app) {try{
mapper.add(app);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@Overridepublic booleandelete(String appAccount) {try{
mapper.delete(appAccount);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@Overridepublic booleanupdate(Application app) {try{
mapper.update(app);return true;
}catch(DataAccessException e) {
e.printStackTrace();
}return false;
}
@OverridepublicApplication findByAppAccount(String appAccount) {try{
Application findByAppAccount=mapper.findByAppAccount(appAccount);returnfindByAppAccount;
}catch(DataAccessException e) {
e.printStackTrace();
}return null;
}
@Overridepublic ListfindAll() {try{returnmapper.findAll();
}catch(DataAccessException e) {
e.printStackTrace();
}return null;
}
}
自行设计的DAO层对象容器(在DAO对象很多时,如果在service层要调用对应的DAO还得手动注入,通过引用这个DAO层对象容器,可以实现在需要使用DAO时迅速找需要的DAO,省去了繁杂的手动注入,而且spring默认的bean都是单例的,无论在何处注入一个实体bean其实都是同一个。这样做更方便):
packagecom.pinche.statistic.dao;importjava.lang.reflect.Field;importjavax.annotation.PostConstruct;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Repository;
@Repositorypublic classBaseDAL {private static final Logger logger = LoggerFactory.getLogger(BaseDAL.class);
@AutowiredprivateAppDao _appDao;public staticAppDao appDao;
@AutowiredprivateMetaDataDao _metaDataDao;public staticMetaDataDao metaDataDao;
@AutowiredprivateDDLManager _DDLManager;public staticDDLManager DDLManager;
@AutowiredprivateAnalyzeDao _analyzeDao;public staticAnalyzeDao analyzeDao;
@AutowiredprivateDialstatisticsDao _dialstatisticsDao;public staticDialstatisticsDao dialstatisticsDao;
@PostConstructpublic voidinit() {long start =System.currentTimeMillis();
logger.debug("start init BaseDAL ...");try{
Field[] fields= this.getClass().getDeclaredFields();for (int i = 0; i < fields.length; i++) {
String fieldname=fields[i].getName();if (fieldname.startsWith("_")) {
String sfieldname= fieldname.substring(1);
Field sfield= this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseDAL OVER, consume = {}ms",
System.currentTimeMillis()-start);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(NoSuchFieldException e) {
e.printStackTrace();
}catch(SecurityException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
如果使用了以上的层管理容器,如果要在容器中添加一个DAO(例如:DemoDao),只需在这个容器中添加一个这样的声明:
@AutowiredprivateDemoDao _demoDao;public static DemoDao demoDao;
packagecom.pinche.statistic.service;importjava.util.List;importcom.pinche.statistic.domain.Application;/***@authorJACKWANG
*@sinceDec 23, 2013*/
public interfaceAppService {
Application find(String appAccount);booleanupdate(Application app);booleansetDisable(String appAccount);booleansetEnable(String appAccount);
ListfindAll();
}
packagecom.pinche.statistic.service.impl;importjava.util.List;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Service;importcom.pinche.statistic.dao.BaseDAL;importcom.pinche.statistic.domain.Application;importcom.pinche.statistic.service.AppService;importcom.pinche.statistic.utils.SystemUtils;/***@authorJACKWANG
*@sinceDec 23, 2013*/@Servicepublic class AppServiceImpl implementsAppService {private static final Logger logger =LoggerFactory
.getLogger(AppServiceImpl.class);
@OverridepublicApplication find(String appAccount) {returnBaseDAL.appDao.findByAppAccount(appAccount);
}
@Overridepublic booleanupdate(Application app) {
String appAccount=app.getAppAccount();if (appAccount == null && "".equals(appAccount)) {return true;
}returnBaseDAL.appDao.update(app);
}
@Overridepublic booleansetDisable(String appAccount) {
Application app= newApplication();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_DISABLE);returnBaseDAL.appDao.update(app);
}
@Overridepublic booleansetEnable(String appAccount) {
Application app= newApplication();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_ENABLE);returnBaseDAL.appDao.update(app);
}
@Overridepublic ListfindAll() {returnBaseDAL.appDao.findAll();
}
}
哈哈,使用层对象管理容器是不是很方便。通过一个引用就能获得所有的DAO支持。所以我在service层也构建了一个service层对象管理容器BaseBLL:
packagecom.pinche.statistic.service;importjava.lang.reflect.Field;importjavax.annotation.PostConstruct;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;/***@authorJACKWANG
*@sinceDec 23, 2013*/@Servicepublic classBaseBLL {private static final Logger logger = LoggerFactory.getLogger(BaseBLL.class);
@AutowiredprivateAnalyzeService _analyzeService;public staticAnalyzeService analyzeService;
@AutowiredprivateAppService _appService;public staticAppService appService;
@AutowiredprivateMetaDataService _metaDataService;public staticMetaDataService metaDataService;
@PostConstructpublic voidinit() {long start =System.currentTimeMillis();
logger.debug("start init BaseBLL ...");try{
Field[] fields= this.getClass().getDeclaredFields();for (int i = 0; i < fields.length; i++) {
String fieldname=fields[i].getName();if (fieldname.startsWith("_")) {
String sfieldname= fieldname.substring(1);
Field sfield= this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseBLL OVER, consume = {}ms",
System.currentTimeMillis()-start);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(NoSuchFieldException e) {
e.printStackTrace();
}catch(SecurityException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
好了下面应该是controller层的编写了,但是由于笔者以上的代码只是摘录了系统中的部分,而在controller中涉及到其他的内容,如果直接摘录可能和以上的代码衔接不上。所以这里就不进行了controller层的具体介绍了。本系统controller层使用的是SpringMVC,开发效率一级赞。