这篇文章介绍如何在Spring boot中整合Mybatis,其中sql语句采用注解的方式插入。后续文章将会介绍,如何使用xml方式。

SSM SSH框架已经满足轻量级这个需求了,但是对于开发人员而言,它们有个缺点,那就是需要的配置文件文件太多。

用这些框架写的项目在resource下面你总是能看到一大堆的xml文件,即使后来注解帮助我们减轻了一部分工作量,但对一个需要迅速动手开发的团队而言,这些远远不够。

针对这些需求,Spring Boot出现了。采用“习惯大于约定”的思想解决了这一难题。不需要任何xml配置文件,我们就可以写出一个web项目。

当然,并不是说Sping Boot是一种新的出现,在我看来,它只是根据人们日常开发的习惯将Spring SpringMVC进行整合,让它能够快速满足大多数人的需求。

同时,Spring Boot的缺点也很明显,封装过于良好,细节不为人知。当我们需要“习惯”之外的东西或者出现异常的错误,我们往往束手无策。

好了,废话不多说了。下面介绍,如何将Spring Boot与MyBatis进行整合。

步骤一:这个网站中下载初始工程,当然你也可以在eclipse中新建maven web项目。

步骤二:通过eclipse将该工程导入。

步骤三:打开pom.xml,里面添加MySQL和MyBatis的依赖。

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency> <!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> </dependencies>

步骤四:准备测试数据

CREATE TABLE IF NOT EXISTS `student`(
`id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`gender` ENUM('female','male') NOT NULL,
`stu_id` VARCHAR(50) NOT NULL,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into student(name,gender,stu_id) values('Andy','female','01'),('Bruce','male','02'),('Celina','female','03'),('David','male','04');

步骤五:在Application.properties中添加MySQL的配置信息,并配置数据源信息。

spring.datasource.url = jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
     @Autowired
private Environment env; //destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DataSource dataSource = new DataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);//初始化时建立物理连接的个数
dataSource.setMaxActive(20);//最大连接池数量
dataSource.setMinIdle(0);//最小连接池数量
dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。 return dataSource;
}

步骤六:编写student表对应的POJO类。

package com.lkb.demo.domain;

/**
* student表对应的POJO类
* @author LKB
*
*/
public class Student {
/**
* id
*/
private int id;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private String gender;
/**
* 学号
*/
private String stuId;
//get set
...
}

步骤七:编写Mapper接口。在方法上面添加对应的mybatis注解,这里我是选择,所以添加的是@Select 。

package com.lkb.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.lkb.demo.domain.Student;

public interface StudentMapper {

    /**
* 查找所有的学生
* @return
*/
@Select("select * from student where 1=1")
public List<Student> selectAll();
}

步骤八:编写service接口。

package com.lkb.demo.service;

import java.util.List;

import com.lkb.demo.domain.Student;

public interface StudentService {

    /**
* 获取所有学生信息
* @return
*/
public List<Student> getAllStu();
}

步骤九:编写service接口实现类。

package com.lkb.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.lkb.demo.domain.Student;
import com.lkb.demo.mapper.StudentMapper;
import com.lkb.demo.service.StudentService; @Service("studentService")
public class StudentServiceImpl implements StudentService{ @Autowired
StudentMapper studentMapper; @Override
public List<Student> getAllStu() {
// TODO Auto-generated method stub
return studentMapper.selectAll();
} }

步骤十:编写controller类。与之前不同的是,这里有一个@RestController 的注解,其实这个注解就是@Controller与@ResponseBody的结合。

你可以写一个@RestController,也可以按照之前的习惯书写。

package com.lkb.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.lkb.demo.domain.Student;
import com.lkb.demo.service.StudentService; @RestController
@RequestMapping("/stu")
public class StudentController { @Autowired
StudentService stuService; /**
* 获取所有学生
* @return
*/
@RequestMapping("/getAll")
public String getAllStu(){
List<Student> students = stuService.getAllStu();
return students.toString();
}
}

步骤十一:编写启动类。下载的项目中已经带有启动类。但是我们仍然要添加mapper的路径,告诉Spring Boot上哪寻找我们的Mapper文件。

@SpringBootApplication
@MapperScan("com.lkb.demo.mapper")
public class DemoApplication{ public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

步骤十二:在启动类处点击run->run as java application。下面是启动界面。

步骤十三:在浏览器输入localhost:8080/stu/getAll

可以看到是有返回数据的。

Spring Boot 整合MyBatis(1)的更多相关文章

  1. Spring Boot整合Mybatis并完成CRUD操作

    MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...

  2. spring boot 整合 mybatis 以及原理

    同上一篇文章一样,spring boot 整合 mybatis过程中没有看见SqlSessionFactory,sqlsession(sqlsessionTemplate),就连在spring框架整合 ...

  3. Spring Boot 整合mybatis时遇到的mapper接口不能注入的问题

    现实情况是这样的,因为在练习spring boot整合mybatis,所以自己新建了个项目做测试,可是在idea里面mapper接口注入报错,后来百度查询了下,把idea的注入等级设置为了warnin ...

  4. Spring Boot整合Mybatis报错InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    Spring Boot整合Mybatis时一直报错 后来发现原来主配置类上的MapperScan导错了包 由于我使用了通用Mapper,所以应该导入通用mapper这个包

  5. Spring Boot整合MyBatis(非注解版)

    Spring Boot整合MyBatis(非注解版),开发时采用的时IDEA,JDK1.8 直接上图: 文件夹不存在,创建一个新的路径文件夹 创建完成目录结构如下: 本人第一步习惯先把需要的包结构创建 ...

  6. Spring Boot整合Mybatis完成级联一对多CRUD操作

    在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...

  7. Spring Boot系列(三):Spring Boot整合Mybatis源码解析

    一.Mybatis回顾 1.MyBatis介绍 Mybatis是一个半ORM框架,它使用简单的 XML 或注解用于配置和原始映射,将接口和Java的POJOs(普通的Java 对象)映射成数据库中的记 ...

  8. 太妙了!Spring boot 整合 Mybatis Druid,还能配置监控?

    Spring boot 整合 Mybatis Druid并配置监控 添加依赖 <!--druid--> <dependency> <groupId>com.alib ...

  9. Spring Boot 整合 Mybatis 实现 Druid 多数据源详解

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...

  10. Spring boot整合Mybatis

    时隔两个月的再来写博客的感觉怎么样呢,只能用“棒”来形容了.闲话少说,直接入正题,之前的博客中有说过,将spring与mybatis整个后开发会更爽,基于现在springboot已经成为整个业界开发主 ...

随机推荐

  1. MyBatis操作oracle的一些问题加载

    mybatis在更新数据或者插入数据为空的时候必须指定jdbcType类型 1:传入的参数是对象类型 User user =new User(); INSERT INTO t_user ( id, u ...

  2. 有向图博弈+出度的结合 Codeforces Round #406 (Div. 2) C

    http://codeforces.com/contest/787/problem/C 题目大意:有一个长度为n的环,第1个位置是黑洞,其他都是星球.已知在星球上(不含第一个黑洞)有一位神.有两个人, ...

  3. vector的哈希值 Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) C

    http://codeforces.com/contest/757/problem/C 题目大意:有n个导管,每个体育馆有k种神奇宝贝,然后所有的n个体育馆中,一共有m中神奇宝贝.可知,每个神奇宝贝中 ...

  4. Python学习笔记(四十六)网络编程(2)— UDP编程

    摘抄:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320049779 ...

  5. JVM调优总结(5):典型配置

    以下配置主要针对分代垃圾回收算法而言. 堆大小设置 年轻代的设置很关键 JVM中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制:系统的可用虚拟内存限制:系统的可用物理 ...

  6. 前端开发必知必会:CSS Position 全解析

    此文根据Steven Bradley的<How Well Do You Understand CSS Positioning?>所译,整个译文带有我自己的理解与思想,如果译得不好或不对之处 ...

  7. 《JavaScript 实战》:JavaScript 实现拖拽缩放效果

    拖拉缩放效果,实现通过鼠标拖动来调整层的面积(宽高)大小,例如选框效果.这里的拖拉缩放比一般的选框复杂一点,能设置八个方位(方向)的固定触发点,能设置最小范围,最大范围和比例缩放. 跟拖放效果一样,程 ...

  8. 【CodeForces】889 B. Restoration of string

    [题目]B. Restoration of string [题意]当一个字符串在字符串S中的出现次数不小于任意子串的出现次数时,定义这个字符串是高频字符串.给定n个字符串,求构造出最短的字符串S满足着 ...

  9. 《Troubleshooting SQL Server》读书笔记-CPU使用率过高(上)

    第三章 High CPU Utilization. CPU使用率过高问题很容易被发现,但是诊断却不是很容易.CPU使用过高很多时候会成为其它问题的替罪羊,所以在确认和故障诊断时要抽丝剥茧. 调查CPU ...

  10. 【leetcode 简单】第三十九题 Excel表列名称

    给定一个正整数,返回它在 Excel 表中相对应的列名称. 例如, 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> ...