本文适用于初学者:

该文主要教大家如何整合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

测试结果:

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

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

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

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

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

  3. Java开发学习(十四)----Spring整合Mybatis及Junit

    一.Spring整合Mybatis思路分析 1.1 环境准备 步骤1:准备数据库表 Mybatis是来操作数据库表,所以先创建一个数据库及表 create database spring_db cha ...

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

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

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

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

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

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

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

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

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

  9. spring整合mybatis(hibernate)配置

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

随机推荐

  1. Struts2-学习笔记系列(5)-配置action

    配置包命名空间 实现了action就需要在struts中配置action.首先配置包属性: 需要注意的是:在框架进行包匹配的时候,按文档的从上到下的顺序进行匹配   <!--下面配置名为book ...

  2. python3(四十)datetime timestamp str

    """时间处理 """ __author__on__ = 'shaozhiqi 2019/9/25' # !/usr/bin/env pyt ...

  3. AJ学IOS(27)UI之iOSUIKit字符属性NSAttributedString概述

    AJ分享,必须精品 UIKit字符属性NSAttributedString概述 字符属性 字符属性可以应用于 attributed string 的文本中. NSString *const NSFon ...

  4. Python导出数据到Excel表格-NotImplementedError: formatting_info=True not yet implemented

    在使用Python写入数据到Excel表格中时出现报错信息记录:“NotImplementedError: formatting_info=True not yet implemented” 报错分析 ...

  5. L26 使用卷积及循环神经网络进行文本分类

    文本情感分类 文本分类是自然语言处理的一个常见任务,它把一段不定长的文本序列变换为文本的类别.本节关注它的一个子问题:使用文本情感分类来分析文本作者的情绪.这个问题也叫情感分析,并有着广泛的应用. 同 ...

  6. 后端code review finished 12-28

    今天只有天赋和士杰有相应的后端代码的code review工作,因为并没有召开daily scrum.只是天赋和士杰对后端所有的代码进行了review,对代码进行了整理并删除了一些残留的0 refre ...

  7. golang slice 源码解读

    本文从源码角度学习 golang slice 的创建.扩容,深拷贝的实现. 内部数据结构 slice 仅有三个字段,其中array 是保存数据的部分,len 字段为长度,cap 为容量. type s ...

  8. 原创Hbase1.2.1集群安装

    [hadoop@Hmaster install]$ tar -zxvf hbase-1.2.1-bin.tar.gz -C ~ [hadoop@Hmaster install]$vi ~/.bash_ ...

  9. (一)C# Windows Mobile 半透明窗体

    Windows Mobile,个人心中臻至完美的系统. 不忍自己对WM的钻研成果消逝,故留作纪念. 系列开篇,便是一个曾令自己困扰很久的问题:如何实现半透明窗体. 如果了解Win32编程,其实很简单. ...

  10. pytorch 矩阵数据增加维度unsqueeze和降低维度squeeze

    增加一个维度 out.unsqueeze(-1) 降低一个维度 out.squeeze(dim=1)