1 选择mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
2 选择mybatis orm
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
3 配置mysql和mybatis
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapperLocations=classpath:mapper/*.xml
4 Mapper和Mapper xml
它们是一一对应的,Mapper xml中负责sql的编写,Mapper负责在业务中执行相应的操作。
package com.hello.springboot.mapper;
import com.hello.springboot.entity.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
User findById(Long id);
void insert(User user);
void update(User user);
void delete(Long id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace是命名空间,是mapper接口的全路径-->
<mapper namespace="com.hello.springboot.mapper.UserMapper">
// 注意,这里的namespace和对应的dao的接口名一致。
<!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象-->
<resultMap id="userResultMap" type="com.hello.springboot.entity.User">
<id property="name" column="username"></id>
</resultMap>
<!--sql – 可被其他语句引用的可重用语句块-->
<sql id="colums">
id,username,age,pwd
</sql>
<select id="findAll" resultMap="userResultMap">
select
<include refid="colums" />
from user
</select>
<select id="findById" resultMap="userResultMap">
select
<include refid="colums" />
from user
where id=#{id}
</select>
<insert id="insert" parameterType="com.hello.springboot.entity.User" >
INSERT INTO
user
(username,age,pwd)
VALUES
(#{name}, #{age}, #{pwd})
</insert>
<update id="update" parameterType="com.hello.springboot.entity.User" >
UPDATE
users
SET
<if test="username != null">username = #{username},</if>
<if test="pwd != null">pwd = #{pwd},</if>
username = #{username}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
user
WHERE
id =#{id}
</delete>
</mapper>
三点要注意:
第一,Mapper xml中的namespace就是Mapper接口;
第二,Mapper接口中的方法的名字要和Mapper xml中操作的名字一样;
第三,注意参数;
5 在代码中使用dao层的接口
@Resource
UserMapper userMapper;
6 在Application类中加上注释
即Mappers所在的目录,必须要加上这个注释,否则spring发现不了这个bean。
@MapperScan("xxx.mapper")