Spring集成mybatis,也就是SqlSessionFactory、SqlSession不需要硬编码去创建,而是通过Spring的IOC能力,注入到程序中。
最简单案例
maven依赖 (直接添加spring-webmvc,它依赖的其他包会自动载入
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
resources/spring/spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<!-- 引入外部jdbc配置信息 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- mysql数据源配置 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- Mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- mapper xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
</bean>
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- java mapper 接口 -->
<property name="basePackage" value="com.lz.demo.dao.mapper" />
</bean>
</beans>
resources/spring/spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.lz.demo.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
resources/jdbc.properties (用户变量名不要用username,否则会与环境中冲突。报 JDBC连接错误,没有权限。)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
password=luzhen
resources/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>
<!-- 数据源、mapper配置都在spring-mybatis.xml中配置好了,这里只是简单配置一下别名 -->
<typeAliases>
<package name="com.lz.demo.dao.model"/>
</typeAliases>
</configuration>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mybatis.xml</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
resources/log4j.properties(一定要配置log,这样程序出错,就会更容易找到问题错在)
log4j.rootLogger=DEBUG, stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
com.lz.demo.dao.model.Role.java
package com.lz.demo.dao.model;
public class Role {
private Integer id;
private String roleName;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
com.lz.demo.dao.mapper.RoleMapper.java
package com.lz.demo.dao.mapper;
import com.lz.demo.dao.model.Role;
public interface RoleMapper {
Role getRoleById(Integer id);
}
resources/mapper/RoleMapper.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">
<mapper namespace="com.lz.demo.dao.mapper.RoleMapper">
<resultMap type="Role" id="RoleResultMap">
<id property="id" column="id"/>
<result property="roleName" column="role_name"/>
<result property="note" column="role"/>
</resultMap>
<sql id="RoleColumnList">
id, role_name, note
</sql>
<select id="getRoleById" parameterType="java.lang.Integer" resultMap="RoleResultMap">
select
<include refid="RoleColumnList"/>
from role
where id = #{id}
</select>
</mapper>
com.lz.demo.controller.HomeController
package com.lz.demo.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.lz.demo.dao.mapper.RoleMapper;
import com.lz.demo.dao.model.Role;
@Controller
public class HomeController {
@Autowired
private RoleMapper roleMapper;
@RequestMapping("/home")
public String home(@RequestParam("id") Integer id, Model model) {
Role role = roleMapper.getRoleById(id);
if (role == null) {
role = new Role();
role.setRoleName("数据库没有ID=" + id + "的Role记录");
role.setNote("这是Java创建的Role");
}
model.addAttribute("role", role);
return "home";
}
}
/WEB-INF/views/home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- web-app_2_3 EL是默认关闭的 要手动打开,这样才能使用${x} -->
<%@ page isELIgnored="false" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>RoleName: ${role.roleName}</div>
<div>Note: ${role.note}</div>
</body>
</html>
启动Web应用,访问 http://localhost:8080/spring_mybatis/home?id=10001