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);
    }
}
时间: 2024-12-22 19:07:14

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

mybatis与spring整合(基于配置文件)(转)

mybatis与spring整合(基于配置文件) 本文主要介绍了如何将mybatis和spring整合在一起使用,本人使用的是mybatis3.05 + spring3.1.0M2 ,使用dbcp作为数据库连接池. 1.编写数据访问接口(UserDao.java) package com.mybatis; publicinterface UserDao { publicint countAll(); } 2.编写数据访问接口映射文件(UserDaoMapper.xml) <?xml versio

MyBatis入门第2天--MyBatis与Spring整合及逆向工程

文档版本 开发工具 测试平台 工程名字 日期 作者 备注 V1.0 2016.06.28 lutianfei none spring和mybatis整合 整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession.(spring和mybatis整合自动完成) 持久层的mapper都需要由spring进行管理. 整合环境 创建一个新的java工程(接近实际开发的工程结构

spring boot 连接mysql 错误The server time zone value &#39;&#214;&#208;&#185;&#250;&#177;&#234;&#215;&#188;&#202;&#177;&#188;&#228;&#39; is unrecognized or represents more than one

1.spring boot 整合mybatis 连接mysql时错误 The server time zone value '?D1ú±ê×?ê±??' is unrecognized or represents more than one 2.解决: jdbc:mysql://localhost:3306/new_schema?useSSL=false&serverTimezone=GMT%2B8 在地址后面加上 &serverTimezone=GMT%2B8%2B是+号的意思,这个意思

Mybatis和Spring整合&amp;逆向工程

Mybatis和Spring整合&逆向工程Mybatis和Spring整合mybatis整合Spring的思路目的就是将在SqlMapConfig.xml中的配置移植到Spring的applicationContext.xml文件中让spring管理SqlSessionFactory让spring管理mapper对象和dao.使用spring和mybatis整合开发mapper代理及原始dao接口.自动开启事务,自动关闭 sqlsession.让spring管理数据源( 数据库连接池)导入相关的

mybatis与spring整合(基于配置文件)

本文主要介绍了如何将mybatis和spring整合在一起使用,本人使用的是mybatis3.05 + spring3.1.0M2 ,使用dbcp作为数据库连接池. 1.编写数据访问接口(UserDao.java) package com.mybatis;public interface UserDao { public int countAll();} 2.编写数据访问接口映射文件(UserDaoMapper.xml) <?xml version="1.0" encoding=

【MyBatis学习14】MyBatis和Spring整合

前面十几篇博文总结了mybatis在开发中的相关技术,但在实际中都是和spring整合开发的,所以这里总结一下mybatis和spring的整合方法,并在整合后进行测试. 1. 整合的环境 这都是老掉牙的问题了,不管是开发还是整合,首先环境肯定得有,环境嘛,除了Java环境和开发环境外,那就是jar包咯,关于mybatis和spring整合的jar包,我已经上传到下载频道了==>传送门  http://download.csdn.net/detail/eson_15/9549624 将这些jar

MyBatis学习(三)---MyBatis和Spring整合

想要了解MyBatis基础的朋友可以通过传送门: MyBatis学习(一)---配置文件,Mapper接口和动态SQL http://www.cnblogs.com/ghq120/p/8322302.html MyBatis学习(二)---数据表之间关联 http://www.cnblogs.com/ghq120/p/8323918.html 之前两篇文章都是单独介绍了MyBatis的用法,并没有和任何框架进行整合.使用MyBatis完成数据库的操作仍有一些模板化的代码,比如关闭SqlSessi

Mybatis与Spring整合

Mybatis与Spring整合无外乎要将数据源,以及事物管理的相关配置交给spring来管理,mybatis配置负责sqlmapper的相关配置也就是dao层到sql映射的相关配置. 一下以手机管理系统dao层实现所用到的Spring与MyBatis整合为例. 1.spring中beans.xml相关配置 <!--加载数据源基本配置文件--><context:property-placeholder location="classpath:conf/jdbc.properti

mybatis与spring整合时读取properties问题的解决

在学习mybatis与spring整合是,想从外部引用一个db.properties数据库配置文件,在配置文件中使用占位符进行引用,如下: 1 <context:property-placeholder location="classpath:db.properties" /> 2 <bean id="dataSource" 3 class="org.springframework.jdbc.datasource.DriverManage