Spring整合Mybatis方案二與AOP事務(wù)

之前介紹的方法是不生成Example 以及 Dao
但是第二種方案里面是全部自動生成的 ,這中方案對于持久層幾乎不用寫sql 方便了很多 。

第一步:創(chuàng)建Maven項(xiàng)目,導(dǎo)入依賴
導(dǎo)入的依賴和之前的一模一樣 直接復(fù)制粘貼即可。

第二步:生成實(shí)體類和映射文件(包含Example+DAO)
Mapper代理方式
生成DAO
生成Example,自帶功能更加多。
Mybatis自動生成插件的配置文件如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<classPathEntry location="D:\Program Files\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar" ></classPathEntry>
<context id="context1" >
<commentGenerator>

<property name="suppressAllComments" value="true" />
</commentGenerator>

<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/testmybatis01?characterEncoding=utf-8" userId="root" password="zyh" />

<javaModelGenerator targetPackage="com.zyh.pojo" targetProject="src/main/java" />

<sqlMapGenerator targetPackage="com.zyh.mapper" targetProject="src/main/java" />

<javaClientGenerator targetPackage="com.zyh.dao" targetProject="src/main/java" type="XMLMAPPER" />

<table tableName="t_user_info" domainObjectName="UserInfo">
</table>

</context>
</generatorConfiguration>

生成之后,持久層基本不用再手動編程。常規(guī)的CRUD方法都具備了。這里針對單表操作。
加上Example后生成的能力更多
分別觀察下面箭頭指向的文件,都會發(fā)現(xiàn)里面的方法增多。

image.png

第三步:整合持久層配置
核心:DAO接口掃描,生成DAO接口的代理實(shí)現(xiàn)類。
dao接口掃描,必須到具體包,自動注入給服務(wù)層等使用。
各層根據(jù)需要完整掃描自己需要的包,避免相互沖突。
org.mybatis.spring.mapper.MapperScannerConfigurer

部分的配置文件如下所示:

<!-- 1,配置DBCP的數(shù)據(jù)源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="url" value="jdbc:mysql://localhost:3306/testmybatis01?characterEncoding=utf-8"></property>
    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"></property>
    <property name="username" value="root"></property>
    <property name="password" value="zyh"></property>
</bean>
<!-- 2,創(chuàng)建SqlSessionFactory ,由Spring提供 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 思考mybatis的核心配置部分:數(shù)據(jù)源,注冊實(shí)體 -->
    <property name="dataSource" ref="dataSource"></property>
    <!-- 注冊實(shí)體,模糊匹配多個mapper映射文件-->
    <property name="mapperLocations" value="classpath:com/zyh/mapper/*Mapper.xml"></property>
</bean>
<!-- 3,沒有DAO的具體實(shí)現(xiàn)類,怎么辦?DAO接口掃描動態(tài)生成DAO接口的代理實(shí)現(xiàn)類
不需要加id屬性,這里掃描的是所有的DAO接口。
如何把DAO注入給服務(wù)層呢?使用注解方式:注入Mapper代理接口。使用自動裝配就可以了。
    -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--必須定位到具體的dao接口包 -->
    <property name="basePackage" value="com.zyh.dao"></property>
</bean>

注意:
如何把持久層的對象給服務(wù)層?只需要在服務(wù)層定義接口。通過自動注入的方式注入實(shí)現(xiàn)類。


第四步:開發(fā)服務(wù)層接口和實(shí)現(xiàn)類

public interface UserInfoService {
void addUserInfo(UserInfo userInfo);
void updateUserInfo(UserInfo userInfo);
void deleteUserInfo(Long aLong);
UserInfo queryUserInfo(Long aLong);
List<UserInfo> queryUserInfoLike(String s);
List<UserInfo> queryAllUserInfo();

void updateTwo(UserInfo addUser, UserInfo updateUser);

}

實(shí)現(xiàn)類如下所示 :
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

//如何注入持久層,注入的是DAO的Mapper接口,實(shí)現(xiàn)類不用自己開發(fā),
// 已經(jīng)DAO接口掃描動態(tài)生成代理實(shí)現(xiàn)類
@Autowired
private UserInfoMapper userInfoMapper;


@Override
public void addUserInfo(UserInfo userInfo) {
    userInfoMapper.insertSelective(userInfo);
}

@Override
public void updateUserInfo(UserInfo userInfo) {
    userInfoMapper.updateByPrimaryKeySelective(userInfo);
}

@Override
public void deleteUserInfo(Long aLong) {
    userInfoMapper.deleteByPrimaryKey(aLong);
}

@Override
public UserInfo queryUserInfo(Long aLong) {
    /*
    這個是第二種實(shí)現(xiàn)的方式  這個就是使用第二種里面的例子Example
     */

/*
UserInfoExample example=new UserInfoExample();
UserInfoExample.Criteria criteria = example.createCriteria();
criteria.andUIdEqualTo(aLong);
List<UserInfo> userInfos = userInfoMapper.selectByExample(example);
if(userInfos!=null&&userInfos.size()>0){
return userInfos.get(0);
}
*/

    return userInfoMapper.selectByPrimaryKey(aLong);


}

@Override
public List<UserInfo> queryUserInfoLike(String s)
{
    UserInfoExample example=new UserInfoExample();
    UserInfoExample.Criteria criteria = example.createCriteria();
    criteria.andUNameLike("%"+s+"%");
    return   userInfoMapper.selectByExample(example);
}

@Override
public List<UserInfo> queryAllUserInfo() {
    UserInfoExample example=new UserInfoExample();
    return  userInfoMapper.selectByExample(example);
}

@Override
@Transactional(value = "transactionManager")
public void updateTwo(UserInfo addUser, UserInfo updateUser) {
    addUserInfo(addUser);
    updateUserInfo(updateUser);

}

}


注意:
上面的根據(jù)Id 查找 ,使用了兩種方式完成 ,特別需要 注意第二種方式 ,
以及下面的模糊查詢 ,也是通過提供的模板 ,進(jìn)行的查詢 ,這個是方式可以完成 更多的條件的的查詢 ,我們可以好好研究一下第二種方式 ,就沒必要自己拼接sql ,直接使用提供給的方法。


拓展 : 觀察 第二種 查詢方法的 底層模板

1,userinfoMapper.selectByExample(example)這個方法對應(yīng)誰?在mapper的映射文件應(yīng)該有一個同樣名稱的id 對應(yīng)的動態(tài)SQL


image.png

2,這個動態(tài)SQL的豐富功能在什么地方?


image.png

底層的做法:
image.png

加條件的地方在:


image.png

3,分析Example類
criteria.andUidEqualTo(id);//設(shè)置條件


image.png

發(fā)現(xiàn)會拼接SQL。
回到mapper映射文件是:

image.png

最后拼接出來的條件是:

<where> and ${criterion.condition} #{criterion.value}
select * from userinfo <where> and uid= id//傳的動態(tài)值
轉(zhuǎn)化:
select * from userinfo where uid= id

第五步:整合服務(wù)層+AOP配置


<context:component-scan base-package="com.zyh.service"></context:component-scan>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"></property>
</bean>

<tx:advice id="MyAdive" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete
" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query
" read-only="true"/>
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="MyPoint" expression="execution(* com.zyh.service..(..))"></aop:pointcut>
<aop:advisor advice-ref="MyAdive" pointcut-ref="MyPoint"></aop:advisor>
</aop:config>

DAO與Service掃描別混淆

第六步:整合測試

測試方法如下所示:
@Test
public void testInsert(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
UserInfo user=new UserInfo();
user.setuName("我是第二種方法");
user.setuPass("我是第二總方法");
userInfoService.addUserInfo(user);
}
@Test
public void testDelete(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
userInfoService.deleteUserInfo(12l);
}
@Test
public void testUpdate(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
UserInfo user=new UserInfo();
user.setuName("我是第二種方法");
user.setuPass("我是第二總方法");
user.setuId(12l);
userInfoService.updateUserInfo(user);
}
@Test
public void queryById(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
UserInfo userInfo = userInfoService.queryUserInfo(12l);
Log.info(userInfo);
}
@Test
public void queryALL(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
List<UserInfo> userInfos = userInfoService.queryAllUserInfo();
Log.info(userInfos);
}
@Test
public void queryLike(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserInfoService userInfoService = (UserInfoService) classPathXmlApplicationContext.getBean("userInfoService");
List<UserInfo> userInfos = userInfoService.queryUserInfoLike("張");
for (UserInfo userInfo : userInfos) {
Log.info(userInfo);
}
}

總結(jié):
持久層:生成DAO接口,使用Mapper掃描的方式生成代理實(shí)現(xiàn)類
服務(wù)層:
直接注入DAO接口,使用自動裝配,本身也使用注解。不需要在配置文件中創(chuàng)建對象。
服務(wù)層開始具體實(shí)現(xiàn)的時(shí)候,使用了Example類提供的復(fù)雜條件查詢能力。
AOP部分和方案一一致。

AOP方案二--注解

觀察上面的整合 你會發(fā)現(xiàn) 在AOP 事物整合的時(shí)候 配置文件很亂,這里我們提供另一種方式來完成 即 注解方式

修改spring配置文件:

將下面兩個部分替換之前的 步驟 5、6、7

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"></property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

第二步:目標(biāo)類或目標(biāo)方法添加注解@Transactional即可
org.springframework.transaction.annotation.Transactional

如下在服務(wù)接口的實(shí)現(xiàn)類里面:
@Override
@Transactional(value = "transactionManager")
public void updateTwo(UserInfo addUser, UserInfo updateUser) {
addUserInfo(addUser);
updateUserInfo(updateUser);
}

如果加在類上需要注意編譯級別:


image.png

點(diǎn)擊紅色燈泡或者alt+enter


image.png

image.png

級別調(diào)整為警告:


image.png

綜上 :我們采用了注解加上配置文件的開發(fā)方式,所以這時(shí)候我們總結(jié)一下注解:
常規(guī)注解:
持久層注解@Repository 這里使用是Mapper代理
服務(wù)層注解@Service
注入注解@Autowired@Qualifier
開啟注解掃描<context:component-scan
事務(wù)注解:
@Transactional 建議加在方法上
開啟事務(wù)注解:tx:annotation-driven

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內(nèi)容