mysql basedal_spring与MyBatis结合
下面將介紹使用spring+mybatis的開發(fā)樣例:
首先,筆者創(chuàng)建的是一個maven工程,在開發(fā)先先導(dǎo)入相關(guān)的依賴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和數(shù)據(jù)庫連接池的配置:
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
在這里要注意,因?yàn)槲沂褂昧藬?shù)據(jù)庫連接池proxool,雖然已經(jīng)設(shè)置servlet的啟動級別是1,但是由于在servlet啟動之前,spring(ContextLoaderListener)監(jiān)聽器已啟動了,所以在spring監(jiān)聽啟動時它會報一個找不到對應(yīng)的數(shù)據(jù)源的SQLException。對于這個問題,本可以通過更改spring為servlet啟動,并將啟動級別設(shè)置為proxool配置加載之后解決:
contextConfigLocation
org.springframework.web.context.ContextLoaderServlet
2
但是因?yàn)閟pring3以后就不支持使用servlet啟動了,官方推薦使用listener啟動applicationContext。所以這個方法在新版本不適合了,不過這個異常可以忽略,因?yàn)閜roxool在整個項(xiàng)目加載完成的時候的確以及完成了加載,所以在項(xiàng)目運(yùn)行起來以后是不會報錯的,開始報錯是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進(jìn)行配置(這里使用了兩個數(shù)據(jù)源):
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
base-package="com.pinche.statistic.dao,
com.pinche.statistic.service" />
Application.java是下面會用到的一個實(shí)體bean:
public classApplication {public static final int APP_DISABLE = 0;public static final int APP_ENABLE = 1;privateInteger id;private String appAccount;//每個app對應(yīng)一個賬戶標(biāo)識;對應(yīng)生成的數(shù)據(jù)表
privateString appName;privateString appICON;privateString appDesc;privateString appURL;privateDate createTime;private int isDisable;//'是否前臺顯示:0顯示,1不顯示'
}
首先我們要編寫一個與mapper.xml文件映射的接口文件,mybatis會將這個接口文件和對應(yīng)的mapper文件中的sql語句關(guān)聯(lián),自動實(shí)現(xiàn)這個接口文件。在之后的開發(fā)中我們直接調(diào)用這個接口文件就可以了,因?yàn)閮?nèi)存中已經(jīng)有接口相對應(yīng)的實(shí)例了。
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文件的配置必須要注意的是它的命名空間是必須的,而且是對應(yīng)接口文件的全名!并且每個sql語句的id屬性和接口文件中的方法名一致!!
下面是ApplicationsMapper.java文件,也就是對應(yīng)的接口文件:
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方法,其他的測試方法大家可以照著寫一寫。如果插入成功恭喜,你的環(huán)境已經(jīng)搭好了。
接下來是將繼續(xù)這個樣例系統(tǒng)的Dao層,service層和controller層。
這個dao層吧,項(xiàng)目中就是這么用的,不過現(xiàn)在通過大家的指正,mybatis提供了@param來解決多參數(shù)問題,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;
}
}
自行設(shè)計的DAO層對象容器(在DAO對象很多時,如果在service層要調(diào)用對應(yīng)的DAO還得手動注入,通過引用這個DAO層對象容器,可以實(shí)現(xiàn)在需要使用DAO時迅速找需要的DAO,省去了繁雜的手動注入,而且spring默認(rèn)的bean都是單例的,無論在何處注入一個實(shí)體bean其實(shí)都是同一個。這樣做更方便):
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層也構(gòu)建了一個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();
}
}
}
好了下面應(yīng)該是controller層的編寫了,但是由于筆者以上的代碼只是摘錄了系統(tǒng)中的部分,而在controller中涉及到其他的內(nèi)容,如果直接摘錄可能和以上的代碼銜接不上。所以這里就不進(jìn)行了controller層的具體介紹了。本系統(tǒng)controller層使用的是SpringMVC,開發(fā)效率一級贊。
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;
}
}
自行設(shè)計的DAO層對象容器(在DAO對象很多時,如果在service層要調(diào)用對應(yīng)的DAO還得手動注入,通過引用這個DAO層對象容器,可以實(shí)現(xiàn)在需要使用DAO時迅速找需要的DAO,省去了繁雜的手動注入,而且spring默認(rèn)的bean都是單例的,無論在何處注入一個實(shí)體bean其實(shí)都是同一個。這樣做更方便):
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層也構(gòu)建了一個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();
}
}
}
好了下面應(yīng)該是controller層的編寫了,但是由于筆者以上的代碼只是摘錄了系統(tǒng)中的部分,而在controller中涉及到其他的內(nèi)容,如果直接摘錄可能和以上的代碼銜接不上。所以這里就不進(jìn)行了controller層的具體介紹了。本系統(tǒng)controller層使用的是SpringMVC,開發(fā)效率一級贊。
總結(jié)
以上是生活随笔為你收集整理的mysql basedal_spring与MyBatis结合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql二维数组vb_VBA链接MYS
- 下一篇: mysql float 精度阶段_mys