一、MyBatis的介绍
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
二、配置
1.注入依赖
![](https://img-blog.csdnimg.cn/20190218173539942.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NhdHRsZV9rbmlmZQ==,size_16,color_FFFFFF,t_70)
<!--放在dependencies标签里-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.配置 application
![](https://img-blog.csdnimg.cn/20190218175240449.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NhdHRsZV9rbmlmZQ==,size_16,color_FFFFFF,t_70)
spring:
datasource:
username: 【用户名】
password: 【密码】
url: jdbc:mysql://【ip地址】:3306/【数据库名】
3.创建JavaBean
4.mapper(dao)层开发
import org.apache.ibatis.annotations.*;
//注解版
@Mapper
public interface MessageMapper {
@Select("select * from 【数据库名】where id=#{id}")
public Message getId(Integer id);
@Delete("delete from 【数据库】where id=#{id}")
public int deleteId(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into 【数据库名】(【字段1】,【字段2】,【字段3】)" +
" values(#【属性1】,#【属性2】,#【属性3】)")
public int insert(【bean类】 【对象】);
@Update("update 【数据库名】set 【字段】=#{【属性】} where id=#{id}")
public int update (【bean类】 【对象】);
}