最近在做Spring整合MyBatis的时候出现异常,查了很多资料也没有解决问题,所以自己研究了下,总算有成果了,现在把我做的demo贴出来做一个记录,也希望能帮助其他人。同时希望牛人们给予指正,谢谢。
一:准备阶段
本工程用的数据库是MySql,所以先建表
-- 建立数据库
CREATE DATABASE SPRINGDB;
USE SPRINGDB;
--建立student表
CREATE TABLE STUDENT_TBL
(
STUDENT_ID VARCHAR(255) PRIMARY KEY,
STUDENT_NAME VARCHAR(10) NOT NULL,
STUDENT_SEX VARCHAR(10),
STUDENT_BIRTHDAY DATE,
CLASS_ID VARCHAR(255)
);
--建立class表
CREATE TABLE CLASS_TBL
(
CLASS_ID VARCHAR(255) PRIMARY KEY,
CLASS_NAME VARCHAR(10) NOT NULL,
);
--插入学生数据INSERT INTO STUDENT_TBL (STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, CLASS_ID) VALUES (123456, 'robin', '男', '1990-08-01', 121546 )
二:Maven环境搭建
推荐一篇文章,写的很好http://limingnihao.iteye.com/blog/830409。
我新建的工程名为:mybatis。
1.pom.xml。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.robin</groupId>
<artifactId>mybatis</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.1.2.RELEASE</spring.version>
<mybatis.version>3.1.1</mybatis.version>
</properties>
<dependencies>
<!-- dbcp connection pool -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>mybatis</finalName>
</build>
</project>
2.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" >
<!-- 区分项目名称,防止默认重名 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>maven.example.root</param-value>
</context-param>
<!-- Spring的log4j监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 字符集 过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring view分发器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!--至于这里用*.html,大家有兴趣可以查下看有什么好处-->
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
3.dispatcher-servlet.xml。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="com.robin" />
<!-- 定义JSP文件的位置 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4.测试类TestController.java
package com.robin.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class TestController {
@RequestMapping(value = "main.html")
public ModelAndView index_jsp() {
mv.addObject("robin", "Hello World!");
mv.setViewName("index");
return mv;
}
@RequestMapping(value = "index.html")
public String index(){
return "index";
}
}
5.index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:out value="${robin}"></c:out>
</body>
</html>
二:Mybatis环境搭建
前提是搭建好springmvc环境。
1.新建实体类
StudentEntity.java
package com.robin.domain;
import java.io.Serializable;
import java.util.Date;
public class StudentEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private ClassEntity classEntity;
private Date studentBirthday;
private String studentID;
private String studentName;
private String studentSex;
public ClassEntity getClassEntity() {
return classEntity;
}
public Date getStudentBirthday() {
return studentBirthday;
}
public String getStudentID() {
return studentID;
}
public String getStudentName() {
return studentName;
}
public String getStudentSex() {
return studentSex;
}
public void setClassEntity(ClassEntity classEntity) {
this.classEntity = classEntity;
}
public void setStudentBirthday(Date studentBirthday) {
this.studentBirthday = studentBirthday;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}
}
ClassEntity.java
package com.robin.domain;
import java.io.Serializable;
public class ClassEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String classID;
private String className;
public String getClassID() {
return classID;
}
public void setClassID(String classID) {
this.classID = classID;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
2.dao
StudentMapper.java 我类名没有按照规范
package com.robin.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.robin.domain.StudentEntity;
@Repository
@Transactional
public interface StudentMapper {
public StudentEntity getStudent(String studentID);
public StudentEntity getStudentAndClass(String studentID);
public List<StudentEntity> getStudentAll();
public void insertStudent(StudentEntity entity);
public void deleteStudent(StudentEntity entity);
public void updateStudent(StudentEntity entity);
}
3.配置文件
首先是dispatcher-servlet.xml,添加数据源并作相应配置。
a.先把连接数据库的文件贴出来mysql.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=1234
这里说明一下,最好用jdbc.****的格式,要不然后面会出现莫名其妙的错误。
b.dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="com.robin" />
<context:property-placeholder location="classpath:mysql.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!--这里要注意,刚开始我用的是注释掉的那句话,但是会报错,查了资料改为了用sqlSessionFactoryBeanName-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
<property name="basePackage" value="com.robin" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!--
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
-->
</bean>
<!-- 定义JSP文件的位置 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
c.mybatis-config.xml mybatis的配置文件
<?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>
<mappers>
<mapper resource="com/robin/maps/StudentMapper.xml" />
</mappers>
</configuration>
d.StudentMapper.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.robin.dao.StudentMapper">
<resultMap type="com.robin.domain.StudentEntity" id="studentResultMap">
<id property="studentID" column="STUDENT_ID"/>
<result property="studentName" column="STUDENT_NAME"/>
<result property="studentSex" column="STUDENT_SEX"/>
<result property="studentBirthday" column="STUDENT_BIRTHDAY"/>
</resultMap>
<!-- 查询学生,根据id -->
<select id="getStudent" parameterType="String" resultType="com.robin.domain.StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_ID = #{studentID}
]]>
</select>
<!-- 查询学生列表 -->
<select id="getStudentAll" resultType="com.robin.domain.StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL
]]>
</select>
</mapper>
以上就是相应的配置文件,不过我只是实现了查询的功能,其他功能并未完善。我的配置文件放的有点乱,最后我会贴出源码,供大家参考。
4.测试类
TestController.java
package com.robin.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.robin.dao.StudentMapper;
import com.robin.domain.StudentEntity;
@Controller
public class TestController {
@Autowired
private StudentMapper studentMapper;
@RequestMapping(value = "main.html")
public ModelAndView index_jsp() {
ModelAndView mv = new ModelAndView();
StudentEntity entity = studentMapper.getStudent("123456");
mv.addObject("robin", entity.getStudentName());
mv.setViewName("index");
return mv;
}
@RequestMapping(value = "index.html")
public String index(){
return "index";
}
}
5.运行结果
三、总结
程序比较简单,只要搭建注意配置文件的相关配置,就应该不会出错。这只是一个demo,不足之处请大家指正。
源码地址:http://download.csdn.net/detail/jingyuansuifeng/4789863