MyBatis和Spring的优点
工欲善其事,必先利其器。开发环境配置好才能正常地编辑和编译代码,就像盖起一座高楼大厦最重要的是打地基。假如要开发Web应用,那么基本离不开数据的存储和处理,也就是离不开数据库。MyBatis解决了JDBC硬编码的问题,把SQL语句配置在了xml文件里,同时mapper映射配置文件可以将数据库操作结果集映射到相应的Java实体类中,十分方便。和Spring整合后,数据库连接池的配置将会放到Spring中,封装JDBC对事务的处理。MyBatis通过SqlSessionFactory来加载全局配置文件和映射配置文件等,初始化出SqlSession会话,提供数据库连接,Spring可以负责管理SqlSessionFactory,管理mapper映射文件,提供事务处理。所以MyBatis和Spring的整合,相得益彰,这篇日志就来看下两者的整合过程,以及使用mapper代理配置后,如何更方便地进行事务处理。
Spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring配置文件 -->
<!-- 添加Spring的xmlns和xsi信息 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载数据库静态属性配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
首先是Spring配置文件,开头声明了xml版本信息1.0和编码信息UTF-8后,接下来在beans标签对中配置xmlns文档信息(类似于URL)。xsi是模式文档信息,即xml规范。之后第21行,配置数据库连接信息,和MyBatis一样,我们把数据库的连接的配置信息放在了外部的文件里,在Spring配置文件中,通过读取外部静态属性文件,来和数据可建立连接,进行交互。Spring使用的也是DBCP数据库连接池(或者说数据源),这样做的好处是,数据库连接配置信息无需写入到应用程序的代码中,与SQL语句无需硬编码道应用程序代码中一样。来看看保存着数据库连接配置信息的外部静态属性文件:
#JDBC
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis_test?characterEncoding=utf-8&useSSL=false
jdbc.username = root
jdbc.password = 12345
用户名密码等信息的参数都配置在了这里面,Spring只要读取它们即可。
回到Spring配置文件上,下一个标签配置数据库连接池:
<!-- 数据源 -->
<bean id="dataSource