日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql basedal_spring与MyBatis结合

發布時間:2025/3/19 数据库 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql basedal_spring与MyBatis结合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

下面將介紹使用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,開發效率一級贊。

總結

以上是生活随笔為你收集整理的mysql basedal_spring与MyBatis结合的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。