SpringBoot(9) SpringBoot整合Mybaties
一、近几年常用的访问数据库的方式和优缺点
1、原始java访问数据库
开发流程麻烦
<1>注册驱动/加载驱动
Class.forName("com.mysql.jdbc.Driver")
<2>建立连接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");
<3>创建Statement
<4>执行SQL语句
<5>处理结果集
<6>关闭连接,释放资源
2、apache dbutils框架
比上一步简单点
官网:https://commons.apache.org/proper/commons-dbutils/
3、jpa框架
spring-data-jpa
jpa在复杂查询的时候性能不是很好
4、Hiberante 解释:ORM:对象关系映射Object Relational Mapping
企业大都喜欢使用hibernate
5、Mybatis框架
互联网行业通常使用mybatis
不提供对象和关系模型的直接映射,半ORM
二、Mybatis准备
1、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
2、加入依赖(可以用 http://start.spring.io/ 下载)
1 <!-- 引入starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
<scope>runtime</scope>
</dependency> <!-- MySQL的JDBC驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入第三方数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
3、在application.properties文件中加入
#可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =password #使用阿里巴巴druid数据源,默认使用自带的
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource #开启控制台打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
注: <1>driver-class-name不需要加入,可以自动识别
<2>数据库连接池可以用自带的 com.zaxxer.hikari.HikariDataSource
<3>加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成
4、启动类增加mapper扫描
@MapperScan("net.xdclass.base_project.mapper")
技巧:保存对象,获取数据库自增id
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
注:开发mapper,参考语法 http://www.mybatis.org/mybatis-3/zh/java-api.html
5、相关资料:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration
https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples
整合问题集合:
https://my.oschina.net/hxflar1314520/blog/1800035
https://blog.csdn.net/tingxuetage/article/details/80179772
6.代码演示
项目结构

启动类
@SpringBootApplication //一个注解顶下面3个
@MapperScan("net.xdclass.base_project.mapper")
public class XdclassApplication { public static void main(String[] args) throws Exception {
SpringApplication.run(XdclassApplication.class, args);
} }
Mapper层的UserMapper
public interface UserMapper {
//推荐使用#{}取值,不要用${},因为存在注入的风险
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(User user);
/**
* 功能描述:查找全部
* @return
*/
@Select("SELECT * FROM user")
@Results({
@Result(column = "create_time",property = "createTime"),
@Result(column = "create_time",property = "createTime")
//javaType = java.util.Date.class
})
List<User> getAll();
/**
* 功能描述:根据id找对象
* @param id
* @return
*/
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(column = "create_time",property = "createTime")
})
User findById(Long id);
/**
* 功能描述:更新对象
* @param user
*/
@Update("UPDATE user SET name=#{name} WHERE id =#{id}")
void update(User user);
/**
* 功能描述:根据id删除用户
* @param userId
*/
@Delete("DELETE FROM user WHERE id =#{userId}")
void delete(Long userId);
}
注:在查找中@Result表示:从表中的column映射到user类中的property。如果有多个用逗号分隔。
Service层的UserService
public interface UserService {
public int add(User user);
}
ServiceImpl层的UserServiceImpl
@Service
public class UserServiceImpl implements UserService{ @Autowired
private UserMapper userMapper; @Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
} }
Controller层的UserController
@RestController
@RequestMapping("/api/v1/user")
public class UserController { @Autowired
private UserService userService; @Autowired
private UserMapper userMapper; /**
* 功能描述: user 保存接口
* @return
*/
@GetMapping("add")
public Object add(){ User user = new User();
user.setAge(11);
user.setCreateTime(new Date());
user.setName("xdclass");
user.setPhone("10010000");
int id = userService.add(user); return JsonData.buildSuccess(id);
} /**
* 功能描述:查找全部用户
* @return
*/
@GetMapping("findAll")
public Object findAll(){ return JsonData.buildSuccess(userMapper.getAll());
} @GetMapping("find_by_id")
public Object findById(long id){
return JsonData.buildSuccess(userMapper.findById(id));
} @GetMapping("del_by_id")
public Object delById(long id){
userMapper.delete(id);
return JsonData.buildSuccess();
} @GetMapping("update")
public Object update(String name,int id){
User user = new User();
user.setName(name);
user.setId(id);
userMapper.update(user);
return JsonData.buildSuccess();
} }
SpringBoot(9) SpringBoot整合Mybaties的更多相关文章
- springBoot(7)---整合Mybaties增删改查
整合Mybaties增删改查 1.填写pom.xml <!-- mybatis依赖jar包 --> <dependency> <groupId>org.mybati ...
- 【SpringBoot】数据库操作之整合Mybaties和事务讲解
========================8.数据库操作之整合Mybaties和事务讲解 ================================ 1.SpringBoot2.x持久化数 ...
- SpringBoot与Mybatis整合方式01(源码分析)
前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...
- Springboot security cas整合方案-实践篇
承接前文Springboot security cas整合方案-原理篇,请在理解原理的情况下再查看实践篇 maven环境 <dependency> <groupId>org.s ...
- Springboot security cas整合方案-原理篇
前言:网络中关于Spring security整合cas的方案有很多例,对于Springboot security整合cas方案则比较少,且有些仿制下来运行也有些错误,所以博主在此篇详细的分析cas原 ...
- 使用Springboot + Gradle快速整合Mybatis-Plus
使用Springboot + Gradle快速整合Mybatis-Plus 作者:Stanley 罗昊 [转载请注明出处和署名,谢谢!] MyBatis-Plus(简称 MP)是一个 MyBatis ...
- springboot 与 shiro 整合 (简洁版)
前言: 网上有很多springboot 与 shiro 整合的资料,有些确实写得很好, 对学习shiro和springboot 都有很大的帮助. 有些朋友比较省事, 直接转发或者复制粘贴.但是没有经过 ...
- springboot+mybatis+springmvc整合实例
以往的ssm框架整合通常有两种形式,一种是xml形式,一种是注解形式,不管是xml还是注解,基本都会有一大堆xml标签配置,其中有很多重复性的.springboot带给我们的恰恰是“零配置”,&quo ...
- SpringBoot 2.x 整合ElasticSearch的demo
SpringBoot 2.x 整合ElasticSearch的demo 1.配置文件application.yml信息 # Tomcat server: tomcat: uri-encoding: U ...
- 30分钟带你了解Springboot与Mybatis整合最佳实践
前言:Springboot怎么使用想必也无需我多言,Mybitas作为实用性极强的ORM框架也深受广大开发人员喜爱,有关如何整合它们的文章在网络上随处可见.但是今天我会从实战的角度出发,谈谈我对二者结 ...
随机推荐
- LCD调试1.0
所谓调lcd timing就是去调lcd时序,一般是6个部分:HFPD(在一行扫描以前需要多少个像素时钟),HBPD(一行扫描结束到下一行扫描开始需要多少个像素时钟),VFPD(一帧开始之前需要多少个 ...
- pip3 install的时候报错timed out
问题: 执行pip install requests报错 Read timed out. 解决方法: 修改超时时间: pip --default-timeout=1000 install -U r ...
- Think twice before starting the adventure
杂文一篇. 1. 取名字真心是一件特别困难的事情.这位独立开发者花了将近两天的时间,给他的私人项目取了个名字:这篇博客<为何我不鸟你的开源项目>里显然还忽视了一个原因,就是名字取得太烂以至 ...
- 《NoSQL精粹》读后感
<NoSQL精粹>作者Pramod J. Sadalaga.Martin Flower著,译者爱飞翔. 本书以关系型数据库开头,讲解了关系型数据库的优缺点,然后引入了NoSQL数据库,并且 ...
- Runtime "Apache Tomcat v6.0 (3)" is invalid. The JRE could not be found. Edit the server and change the JRE location解决方案
使用eclipse,启动Tomcat时出现The JRE could not be found ,Edit server and change teh JRE location的错误提示! 原因:重装 ...
- ubuntu+apache2设置访问、重定向到https
环境:ubunt14裸机,apache2,php5 条件:证书(部分商家买域名送一年),域名,为了方便均在root用户下进行的 web目录:/var/www/test 证书目录(自建):/etc/ap ...
- Exp1 PC平台逆向破解----20164325 王晓蕊
前言:实验中用到的知识 JE:条件转移指令,如果相等则跳转: JNE:条件转移指令(等同于“Jump Not Equal”),如果不相等则跳转: JMP:无条件跳转指令.无条件跳转指令可转到内存中任何 ...
- ORACLE知识点总结
一.ORACEL常用命令 1.解锁账户:ALTER USER username ACCOUNT UNLOCK; 2.查看数据库字符集:SELECT USERENV ('language') FROM ...
- [转] The QCOW2 Image Format
The QCOW2 Image Format https://people.gnome.org/~markmc/qcow-image-format.html The QCOW image format ...
- react-native 项目初始化
react-native 项目初始化 搭建java,android,node环境 http://www.cnblogs.com/morang/p/react-native-java-build.htm ...