Mybatis与Spring整合连接MySQL

1 maven依赖

<dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.framework.version}</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.36</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.1</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-math</artifactId>
      <version>2.2</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>3.1.1.RELEASE</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

2 数据库表

表名为student,位于test库中。

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `name` varchar(20) NOT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

3 数据库表的映射类

package club.chuxing.tech.learn.mybatis.domain;

public class Student {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4 数据库访问DAO

package club.chuxing.tech.learn.mybatis.dao;

import club.chuxing.tech.learn.mybatis.domain.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

@Component
public interface StudentDao {
    @Select("select * from student where id = #{id}")
    Student selectStudent(int id);
}

此DAO不需要对应的Mapper文件。

5 Mybatis配置文件

mybatis.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>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <!-- Continue going here -->
    <typeAliases>
        <typeAlias alias="Student" type="club.chuxing.tech.learn.mybatis.domain.Student" />
    </typeAliases>
</configuration>

6 Spring配置文件

applicationContext-common.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <!--扫描包进行注入-->
    <context:component-scan base-package="club.chuxing.tech.learn.mybatis.dao" />

    <!--创建数据源dataSource对象并注入到SqlSessionFactoryBean对象中-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml" />
        <property name="mapperLocations">
            <list>
                <value>classpath:mybatis-mapper/*Mapper.xml</value>
            </list>
        </property>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"/>
    </bean>

    <!-- 配置扫描Mapper接口的包路径 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 如果是多个包名可用",; \t\n"中任意符号分隔开,详见:MapperScannerConfigurer[269行] -->
        <property name="basePackage" value="club.chuxing.tech.learn.mybatis.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

7 DAO单元测试

package club.chuxing.tech.learn.mybatis.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

import club.chuxing.tech.learn.mybatis.domain.Student;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static club.chuxing.tech.learn.utils.PrintUtil.*;

@ContextConfiguration(locations = "classpath:applicationContext-common.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentDaoTest {
    @Autowired
    private StudentDao dao;
    @Test
    public void testSelectStudent() throws Exception {
        Student student = dao.selectStudent(1);
        print(student);
    }
}

也可以在Main函数中加载DAO bean:

package club.chuxing.tech.learn.mybatis;

import club.chuxing.tech.learn.mybatis.dao.StudentDao;
import club.chuxing.tech.learn.mybatis.domain.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static club.chuxing.tech.learn.utils.PrintUtil.print;

public class MyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-common.xml");
        StudentDao  dao = context.getBean(StudentDao.class);
        Student student = dao.selectStudent(1);
        print(student);
    }
}

转自:http://blog.csdn.net/foreverling/article/details/50987203

时间: 2025-01-29 14:33:53

Mybatis与Spring整合连接MySQL的相关文章

【MyBatis框架】mybatis和spring整合

spring和mybatis整合 1.整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession.(spring和mybatis整合自动完成) 持久层的mapper都需要由spring进行管理. 2.整合环境 创建一个新的java工程(接近实际开发的工程结构) jar包: mybatis3.2.7的jar包 spring3.2.0的jar包 mybatis和sprin

mybatis和spring整合中mapperInterface是做什么用的

问题描述 <bean id="mapDao" class="org.mybatis.spring.MapperFactoryBean"><!-- 这里是接口,不是接口实现类了 --> <property name="mapperInterface" value="com.ssm.iface.IUserDao"/><property name="sqlSessionFactor

Spring整合Mybatis使用&amp;lt;context:property-placeholder&amp;gt;时的坑_java

背景 最近项目要上线,需要开发一个数据迁移程序.程序的主要功能就是将一个数据库里的数据,查询出来经过一系列处理后导入另一个数据库.考虑到开发的方便快捷.自然想到用spring和mybatis整合一下.甚至用mybatis的自动代码生成,可以省下大量dao层的开发. 整合的坑 之前的项目:以前也有过这种类似的程序,就把spring和mybatis整合的配置直接拿来修改下用.之前的整合配置是这样子的: 1.考虑到数据库url.用户名密码的可配置性,将这些信息放入properties文件.在sprin

mybatis 高级映射和spring整合之与Spring整合(6)

mybatis 高级映射和spring整合之mybatis与Spring整合 3.0 mybatis和spring整合(掌握) 3.1 整合思路 需求spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession.(spring和mybatis整合自动完成) 持久层的mapper都需要有spring进行管理. 3.2 整合环境 创建一个新的java工程(接近实际开发的工程结构) jar

mybatis 高级映射和spring整合之高级映射(4)

mybatis 高级映射和spring整合之高级映射 ----------------学习结构-------------------- 0.0 对订单商品数据模型进行分析 1.0 高级映射 1.1 一对一查询 1.2 一对多查询 1.3 多对多查询 1.4 resultMap总结 1.5 延迟加载 2.0 查询缓存 2.1 一级缓存 2.2 二级缓存(了解mybatis二级缓存使用场景) 3.0 mybatis和spring整合(掌握) 4.0 逆向工程(会用) ----------------

mybatis-MyBatis与Spring整合后为什么使用flushCache无效?

问题描述 MyBatis与Spring整合后为什么使用flushCache无效? 代码这样,为什么调用两次这个方法该SQL只会执行一次? @CacheNamespace(implementation=PerpetualCache.class) public interface MapperDao { @Select("SELECT * FROM N1 WHERE ID=#{id}") @Options(useCache=true ,flushCache=true) public Cos

yy-在进行MyBatis与spring问题

问题描述 在进行MyBatis与spring问题 在进行MyBatis与spring整合时不管是使用映射器方法还是纯的XML方法都出现下列问题,查找资料和官方文档都感觉代码与逻辑没有错!!求解答! 下面是是使用映射器方法的spring配置文件beans.xml的内容: 其中UserMapper的代码是: package xx.xx; import java.util.List; import org.apache.ibatis.annotations.Select; import com.yiw

Spring整合MyBatis(Maven+MySQL)图文教程详解_java

一. 使用Maven创建一个Web项目 为了完成Spring4.x与MyBatis3.X的整合更加顺利,先回顾在Maven环境下创建Web项目并使用MyBatis3.X,第一.二点内容多数是回顾过去的内容 . 1.2.点击"File"->"New"->"Other"->输入"Maven",新建一个"Maven Project",如下图所示: 1.2.请勾选"Create a si

mybatis spring 整合 junit测试。 事务不起作用,不提交。删除无效???

问题描述 mybatis spring 整合 junit测试. 事务不起作用,不提交.删除无效??? applicationContext.xml 中的数据库和 sessionFactory以及事务配置 Xml代码 <bean id="bssDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connec