本文适用于初学者:

该文主要教大家如何整合spring和mybatis,整合完成效果,可以从数据库中查询出学生信息:

完整的工程目录如下:

整合思路:

  • 需要spring来管理数据源信息。
  • 需要spring通过单例方式管理SqlSessionFactory。
  • 使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
  • 持久层的mapper都需要由spring进行管理,spring和mybatis整合生成mapper代理对象。

下面开始工程搭建:

第一步:创建工程 File—New—Project

点击Finish完成

注意:项目创建完成会有如下图提示:

这里是问你是否要自动导入,选择Enable即可,maven便会自动帮你导入jar包

第二步:项目准备

本项目需要用到mysql数据库,首先先在mysql中创建一个数据库,然后创建一张表,sql语句如下:

 CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;

 USE `test`;

 /*Table structure for table `student` */

 DROP TABLE IF EXISTS `student`;

 CREATE TABLE `student` (
`id` int(11) DEFAULT NULL,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `student` */ insert into `student`(`id`,`username`,`password`,`email`) values
(1,'jack','','123@jack'),
(2,'rose','','rose@123');

sql语句

第三步:正式开发

(1)、修改pom文件

 <?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.grandage</groupId>
<artifactId>SpringMybatisTest</artifactId>
<version>1.0-SNAPSHOT</version> <properties>
<!-- spring版本号 -->
<spring.version>4.1.6.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- c3p0连接池jar -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies> </project>

POM文件

(2)、新建实体类Student:

 package cn.grandage.pojo;

 public class Student {

     private Integer id;
private String username;
private String password;
private String email; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} @Override
public String toString() {
return "StudentMapper{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}

Student

(3)、新建db.properties文件

 db.driver=com.mysql.jdbc.Driver
#数据库连接字符串(改成自己的连接)
db.url=jdbc:mysql://localhost:3306/test
#数据库用户名(这里改成自己的用户名)
db.username=root
#数据库密码(这里改成自己的密码)
db.password=123456

db.properties

(4)、新建StudentMapper接口

 package cn.grandage.mapper;

 import cn.grandage.pojo.Student;

 public interface StudentMapper {

     public Student findStudentById(int id);
}

StudentMapper

(5)、新建mybatis映射配置文件:

 <?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">
<!-- namespace:命名空间,对sql进行一个分类管理 -->
<!-- 注意:namespace在mapper代理时,具有重要且特殊的作用
对应mapper接口的全限定名
--> <!--mybatis映射配置文件-->
<mapper namespace="cn.grandage.mapper.StudentMapper">
<select id="findStudentById" parameterType="int" resultType="student">
select * from student where id=#{id}
</select>
</mapper>

Student.xml

(6)、新建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>
<!--mybatis核心配置文件--> <!--给类取别名,简化输入,方便映射配置文件中使用-->
<typeAliases>
<typeAlias type="cn.grandage.pojo.Student" alias="student"/>
</typeAliases> <!--加载mapper映射配置文件-->
<mappers>
<mapper resource="Student.xml"/>
</mappers> </configuration>

SqlMapConfig.xml

(7)、新建spring核心配置文件,并整合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>
<!--mybatis核心配置文件--> <!--给类取别名,简化输入,方便映射配置文件中使用-->
<typeAliases>
<typeAlias type="cn.grandage.pojo.Student" alias="student"/>
</typeAliases> <!--加载mapper映射配置文件-->
<mappers>
<mapper resource="Student.xml"/>
</mappers> </configuration>

applicationContext.xml

(8)、测试类编写:

 import cn.grandage.mapper.StudentMapper;
import cn.grandage.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test01 { @Test
public void test01() {
//获取applicationContext文件并加载
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取StudentDao的bean
StudentMapper sd = (StudentMapper) ac.getBean("studentMapper");
Student s = sd.findStudentById(1);
System.out.println("学生姓名:" + s.getUsername());
System.out.println("学生密码:" + s.getPassword());
System.out.println("学生邮箱:" + s.getEmail());
}
}

Test01

测试结果:

Spring整合Mybatis(IDEA版)的更多相关文章

  1. Spring Boot2 系列教程 (十三) | 整合 MyBatis (XML 版)

    前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,之前介绍过了 SpringBoot 整合MyBatis 注解版的使用,上一篇介绍过 MyBatis ...

  2. Spring整合Mybatis报 java.lang.ClassNotFoundException:org.springframework.core.metrics.ApplicationStartup,即:spring的版本过高,采用RELEASE稳定版

    1.遇到的问题: 今天在弄spring整合mybatis的时候遇到一个小问题,如图所示: 简单来说:就是我的spring的xml文件没找到,我就奇了怪了,我所有的配置都没问题啊! 我pom.xml配置 ...

  3. Spring学习总结(六)——Spring整合MyBatis完整示例

    为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简 ...

  4. 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源

    目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...

  5. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二

    接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...

  6. 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  7. 2017年2月16日 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  8. spring整合mybatis错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist

    spring 整合Mybatis 运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:class path reso ...

  9. spring 整合Mybatis 《报错集合,总结更新》

    错误:java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldExcepti ...

  10. spring整合mybatis(hibernate)配置

    一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1. ...

随机推荐

  1. CentOS7 常用命令

    常用命令 1.文件与目录操作 命令 解析 cd /home 进入 ‘/home’ 目录 cd .. 返回上一级目录 cd ../.. 返回上两级目录 cd - 返回上次所在目录 cp file1 fi ...

  2. Flink cep的初步使用

    一.CEP是什么 在应用系统中,总会发生这样或那样的事件,有些事件是用户触发的,有些事件是系统触发的,有些可能是第三方触发的,但它们都可以被看做系统中可观察的状态改变,例如用户登陆应用失败.用户下了一 ...

  3. SpringBoot启动zipkin-server报错Error creating bean with name ‘armeriaServer’

    目前,GitHub 上最新 release 版本是 Zipkin 2.12.9,从 2.12.6 版本开始有个较大的更新,迁移使用 Armeria HTTP 引擎. 从此版本开始,若直接添加依赖的 S ...

  4. [c++] 面试题之犄角旮旯 第壹章

    记录C/C++语言相关的问题. 算法可视化:https://visualgo.net/en <data structure and algorithm in c++> By Adam 有免 ...

  5. node连接数据库

    一.在package.json依赖模块添加: "mysql" : "latest",执行npm install: 二.module目录下新建mysql.js: ...

  6. Wordpress对接小程序配置过程

    最近发现一个很棒的开源项目-WordPress版微信小程序  https://github.com/iamxjb/winxin-app-watch-life.net,详细看了下介绍非常棒,不仅支持的功 ...

  7. CentOS 8 正式发布

    转载请注明:文章转载自 OSCHINA 社区 [http://www.oschina.net] 本文地址:https://www.oschina.net/news/110111/centos-8-re ...

  8. Spring boot 官网学习笔记 - Using Spring Boot without the Parent POM,但是还要使用Parent POM提供的便利

    If you do not want to use the spring-boot-starter-parent, you can still keep the benefit of the depe ...

  9. Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value:

    问题:ERROR JDBCExceptionReporter:72 - Data truncation: Incorrect datetime value: '' for column 'create ...

  10. Java的一些基础知识深入

    1.浅析Java中的final关键字: 2.Java中的static关键字解析: 3.探秘Java中String.StringBuilder以及StringBuffer: 4.Java内部类详解: 5 ...