mybatis+spring配置

时间:2022-04-25 12:13:44

可参考:http://www.javacodegeeks.com/2014/02/building-java-web-application-using-mybatis-with-spring.html

自己对mybatis的spring配置不太熟,弄好了好久总算弄出来了。总结下好了!

1. 新建web maven工程。

以idea自带的spring_mvc模板开个web工程就好。

2. pom.xml配置

pom中需要新增以下jar包

  • mybatis (for MyBatis support)
  • mybatis-spring (for MyBatis-Spring integration support)
  • mysql-connector-java (for MYSQL support)
  • tomcat-jdbc (for Tomcat support MYSQL connection)
  • defind the location of source & resource
<properties>
<spring.version>4.1.3.RELEASE</spring.version>
<mybatis.version>3.3.0</mybatis.version>
<mybatis-spring.version>1.2.3</mybatis-spring.version>
<mysql.version>5.1.21</mysql.version>
<tomcat-jdbc.version>7.0.30</tomcat-jdbc.version>
</properties> <dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat-jdbc.version}</version>
</dependency>
</dependencies>
<build>
<finalName>my_test</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>

3. web.xml

我的实践中web.xml保持原状。

<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

4. 修改mvc-dispatcher-servlet.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
> <!--配置ViewResolver-->
<!--InternalResourceViewResolver支持 servlet、JSP视图解析-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean> <!--配置DataSource数据源-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--Tomcat jdbc pool是apache在tomcat7版本中启用的新连接池,用它来解决以往DBCP无法解决的一些问题-->
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close" autowire="no">
<property name="fairQueue" value="false" />
<property name="minIdle" value="5" />
<property name="maxIdle" value="10" />
<property name="maxActive" value="50" />
<property name="initialSize" value="1" />
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="select 1" />
<property name="validationInterval" value="500000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="30" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/accounts" />
<property name="username" value="name" />
<property name="password" value="passwd" />
</bean> <!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:*.xml" />
</bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<!--查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.springapp.mvc.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean> <context:annotation-config />
<context:component-scan base-package="com.springapp.mvc" /> </beans>

4. 各种类

因为此篇主要想讲讲如果使用在spring中进行mybatis配置,所以代码的分层不太严格。完成后代码树长这样:

mybatis+spring配置

4.1 controller

package com.springapp.mvc;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; @Controller
@RequestMapping("/")
public class HelloController {
@Resource
private SqlSession sqlSession; @RequestMapping(method = RequestMethod.GET)
public ModelAndView test(ModelMap mode){
    //需结合accountMapper.xml来看。Account为namespace的值;getAccountByOwner为select的id值
Account account = sqlSession.selectOne("Account.getAccountByOwner");
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("Account",account);
return mv;
}
}

4.2 Account

package com.springapp.mvc;

import java.math.BigDecimal;

/**
* Created by Administrator on 2015/10/25.
*/
public class Account {
private Integer accountId;
private String account;
private String owner;
private BigDecimal balance; public String getOwner() {
return owner;
} public void setOwner(String owner) {
this.owner = owner;
} public Integer getAccountId() {
return accountId;
} public void setAccountId(Integer accountId) {
this.accountId = accountId;
} public String getAccount() {
return account;
} public void setAccount(String account) {
this.account = account;
} public BigDecimal getBalance() {
return balance;
} public void setBalance(BigDecimal balance) {
this.balance = balance;
} public String toString(){
return "" + this.getAccountId() + "|" + this.getOwner() + "|" +
this.getAccount() + ";"; }
}

4.3 AccountMapper

package com.springapp.mvc.mappers;

import com.springapp.mvc.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository; /**
* Created by Administrator on 2015/11/8.
*/
@Repository
public interface AccountMapper {
//可以使用annotation的方式来进行数据库操作
// @Insert("INSERT INTO accounts(owner,account,type,balance) VALUES"
// + "(#{owner},#{account},#{type},#{balance})")
// @Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true, keyColumn = "id")
// public void insertAccount(Account account); //也可使用xml配置方式来操作数据库,本例中即使用xml来操作数据库
// @Select("SELECT OWNER as owner, ACCOUNT as account, TYPE as type,"
// + "BALANCE as balance FROM accounts WHERE owner=#{owner}")
public Account getAccountByOwner();
}

4.4 accountMapper.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="Account">
<!--select结果与返回类的对应关系 -->
<resultMap id="AccountResult" type="com.springapp.mvc.Account">
<id column="id" jdbcType="INTEGER" property="accountId"/>
<result column="owner" jdbcType="CHAR" property="owner"/>
<result column="account" jdbcType="CHAR" property="account"/>
<result column="balance" jdbcType="DECIMAL" property="balance"/>
</resultMap> <select id="getAccountByOwner" resultMap="AccountResult">
select id, owner, account, balance from accounts where id="1"
</select> </mapper>

4.4 hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
${Account}
</body>
</html>

5. 操作数据库,准备数据

create database accounts;
use accounts;
CREATE TABLE `accounts` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`owner` char(10) NOT NULL,
`account` char(10) DEFAULT NULL,
`balance` decimal(9,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT accounts values(1,'haha', '中国', 12000);

6. 运行tomcat即可搜出刚才插入的数据了。