1,环境准备
在WEB-INF目录下新建lib目录,将依赖的jar包放到该目录下
mybatis相关包的下载地址:http://code.google.com/p/mybatis/downloads/list
DBCP数据源相关包的下载地址:http://commons.apache.org/dbcp/download_dbcp.cgi http://commons.apache.org/pool/download_pool.cgi
在Project -> Properties -> Java Build Path -> Libraries 中增加这些jar包
选中pom.xml右键选择Open With -> Maven POM Editor,打开该文件后在Dependencies中将这些库也加上
2,在Domain Object层新建User类
public class User {
private String mUserId;
private String mUserName;
private String mUserPasswd;
private String mTelePhoneNum;
public String getUserId() {
return mUserId;
}
public void setUserId(String id) {
mUserId = id;
}
........
}
3,在DAO层新增UserMap接口
public interface UserMap {
public User getUser(String id);
}
4,root-context.xml文件中增加以下内容
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/demodb"/>
<property name="username" value="demodb_cat"/>
<property name="password" value="cat"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="resources/mybatis-config.xml"/>
</bean>
<!--mapper bean -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.rain.mvcdemo.dao.UserMap" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
其中DBCP实现了数据库连接池,可以参考http://drizzlewalk.blog.51cto.com/2203401/397982, http://commons.apache.org/dbcp/configuration.html
这里也可以用Tomcat JDBC Connection Pool来替换DBCP,关于两者的比较可以查看,http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/bubinglvservice?characterEncoding=gbk"/>
<property name="username" value="bubinglv"/>
<property name="password" value="bubinglv"/>
</bean>
需要在工程中引入tomcat-jdbc.jar,一般在tomcat的安装目录中可以找到该jar包,无需去网上下载
UserMap接口将由Spring自动实现,在Spring容器中可以通过userMapper这个id获得接口并操作
3,在webapp/resources目录下新增mybatis的配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 配置管理器 -->
<configuration>
<!-- 别名 -->
<typeAliases>
<typeAlias type="com.rain.mvcdemo.pojo.User" alias="User"/>
</typeAliases>
<!-- 映射文件定位 -->
<mappers>
<mapper resource="com/rain/mvcdemo/sqlmap/sqlmap-user.xml" />
</mappers>
</configuration>
4,新增sqlmap文件sqlmap-user.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 整个唯一标识sql的id为namespace+id com.rain.mvcdemo.dao.UserMap.insert-->
<mapper namespace="com.rain.mvcdemo.dao.UserMap">
<resultMap id="userResultMap" type="User">
<id property="mUserId" column="ID"/>
<result property="mUserName" column="NAME"/>
<result property="mUserPasswd" column="PASSWD"/>
<result property="mTelePhoneNum" column="TELEPHONENUM"/>
</resultMap>
<insert id="insertUser" parameterType="User">
insert into users(name, passwd, telephonenum, createdate) values(#{name},#{passwd},#{telephonenum},now())
</insert>
<select id="getUser" parameterType="String" resultType="User" resultMap="userResultMap">
SELECT * FROM users WHERE ID = #{id}
</select>
</mapper>
5,在Controller实现中增加测试代码
该例子仅仅只是快速测试一下mybatis的集成,以下测试均为非正规方法。
一般通过逻辑层调用DAO层的接口,这里简便起见,省略了逻辑层,而是直接让Controller拿着DAO层的接口直接操作。而且较好的方法应该是将UserMap接口通过依赖注入的方式设置给Conntroller,但这里也懒得改Controller的Annotation方式,于是通过ApplicationContext容器来获取UserMap接口实现。Controller原本是拿不到ApplicationContext容器的,一个变通的方式是让Controller类继承ApplicationContextAware接口即可。
@Controller
public class HomeController implements ApplicationContextAware{
........
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(Model model) {
logger.info("Welcome test!.........");
if (this.mctx != null) {
UserMap usermap = (UserMap) this.mctx.getBean("userMapper");
if (usermap != null) {
User sr = usermap.getUser("1");
if (sr != null) {
model.addAttribute("telephoneNum", sr.getTelePhoneNum());
}
}
} else {
logger.info("WebApplicationContext is null");
}
}
6,增加测试页面views/test.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The page is ${telephoneNum}. </P>
</body>
</html>