可参考: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配置,所以代码的分层不太严格。完成后代码树长这样:

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即可搜出刚才插入的数据了。

mybatis+spring配置的更多相关文章

  1. Springmvc + mybatis + spring 配置,spring事物

    今天配置了半天,发现,事物不起效果,主要出现如下错误: org.mybatis.spring.transaction.SpringManagedTransaction] - [JDBC Connect ...

  2. MyBatis学习(一)、MyBatis简介与配置MyBatis+Spring+MySql

    一.MyBatis简介与配置MyBatis+Spring+MySql 1.1MyBatis简介 MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架.MyBatis 摒除了大部分的J ...

  3. MyBatis详解 与配置MyBatis+Spring+MySql

    MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架.MyBatis 摒除了大部分的JDBC代码.手工设置参数和结果集重获.MyBatis 只使用简单的XML 和注解来配置和映射基本 ...

  4. 在spring,mybatis整合配置中走的弯路(1)

    在接触一个新东西,总免不了走一些弯路,也正是在这些弯路中,我们不断的成长. 从git上把之前写的代码扒下来,看看我在当初使用spring与mybatis中所走的弯路,路过的君子也可引以为戒. < ...

  5. 一、MyBatis简介与配置MyBatis+Spring+MySql

    //备注:该博客引自:http://limingnihao.iteye.com/blog/106076 1.1MyBatis简介 MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架 ...

  6. spring和mybatis整合配置

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  7. SSM ( Spring 、 SpringMVC 和 Mybatis )配置详解

    使用 SSM ( Spring . SpringMVC 和 Mybatis )已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没 ...

  8. Mybatis 和 Spring配置

    一.使用的jar包就不详细讲解了,下载了Mybatis 和 Spring 的jar包基本上都添加上去了. 一图概括:(这是我使用的ar包,有些不是Mybatis 和 Spring 的 ) 二. web ...

  9. MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql

    目录(?)[-] 一MyBatis简介与配置MyBatisSpringMySql MyBatis简介 MyBatisSpringMySql简单配置 搭建Spring环境 建立MySql数据库 搭建My ...

随机推荐

  1. 阿里云上部署kafka--遇到的坑

    阿里云防火墙关闭,并且配置规则.不然会导致访问不到服务. 问题一: Caused by: java.net.UnknownHostException: iZuf68tztea6l5ccdz7wemZ: ...

  2. 关于android studio 出现Error:Execution failed for task ':app:preDebugAndroidTestBuild'. 的解决办法

    Error:Execution failed for task ':app:preDebugAndroidTestBuild'. > Conflict with dependency 2018年 ...

  3. Java并发编程的艺术(二)——重排序

    当我们写一个单线程程序时,总以为计算机会一行行地运行代码,然而事实并非如此. 什么是重排序? 重排序指的是编译器.处理器在不改变程序执行结果的前提下,重新排列指令的执行顺序,以达到最佳的运行效率. 重 ...

  4. 开源项目MultiChoiceAdapter详解(三)——MulitChoiceNormalArrayAdapter的使用

    MulitChoiceNormalArrayAdapter是我自己定义的一个类,其实就是实现了MulitChoiceArrayAdapter,为什么做这个简单的实现类呢,因为这样我们在不用Action ...

  5. 《Linux就是这个范儿》

    <Linux就是这个范儿> 基本信息 作者: 赵鑫磊    (加)Jie Zhang(张洁) 丛书名: 图灵原创 出版社:人民邮电出版社 ISBN:9787115359360 上架时间:2 ...

  6. CentOS 7 在vmware中的网络设置

    一环境说明 二centos在vmware中的安装 三NAT网络设置 四设置固定IP 1修改网卡配置说明 2修改etcresolvconf 实现域名解析 五设置防火墙iptables 1 centos安 ...

  7. perf使用示例2

    perf使用示例2 性能调优工具如 perf,Oprofile 等的基本原理都是对被监测对象进行采样,最简单的情形是根据 tick 中断进行采样,即在 tick 中断内触发采样点,在采样点里判断程序当 ...

  8. PO BO VO DTO POJO DAO概念及其作用(附转换图)

    J2EE开发中大量的专业缩略语很是让人迷惑,尤其是跟一些高手讨论问题的时候,三分钟就被人家满口的专业术语喷晕了,PO VO BO DTO POJO DAO,一大堆的就来了(听过老罗对这种现象的批判的朋 ...

  9. 生成学习算法(Generative Learning algorithms)

    一.引言 前面我们谈论到的算法都是在给定\(x\)的情况下直接对\(p(y|x;\theta)\)进行建模.例如,逻辑回归利用\(h_\theta(x)=g(\theta^T x)\)对\(p(y|x ...

  10. [leetcode]Set Matrix Zeroes @ Python

    原题地址:https://oj.leetcode.com/problems/set-matrix-zeroes/ 题意:Given a m x n matrix, if an element is 0 ...