1 选择mysql驱动
mysql
mysql-connector-java
8.0.12
2 选择mybatis orm
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
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 dao dao和Mapper xml
它们是一一对应的,Mapper xml中负责sql的编写,dao负责在业务中执行相应的操作。
package com.hello.springboot.dao;
import com.hello.springboot.entity.User;
import java.util.List;
public interface UserDao {
List findAll();
User findById(Long id);
void insert(User user);
void update(User user);
void delete(Long id);
}
id,username,age,pwd
select
from user
select
from user
where id=#{id}
INSERT INTO
user
(username,age,pwd)
VALUES
(#{name}, #{age}, #{pwd})
UPDATE
users
SET
username = #{username},
pwd = #{pwd},
username = #{username}
WHERE
id = #{id}
DELETE FROM
user
WHERE
id =#{id}
三点要注意:
第一,注意,Mapper xml中的namespace就是对应的dao接口的完整路径名;
第二,Mapper接口中的方法的名字要和Mapper xml中操作的名字一样;
第三,注意参数;
5 在代码中使用dao层的接口
给dao类加上下面的注解,然后就可以像普通的类一样使用dao对象。
@Repository
@Mapper
6 关于dao接口中函数的返回值
第一,调用dao接口时用try catch来进行异常处理,如果出现异常会抛出异常;
第二,在mapper.xml中指定返回值的类型即可,这个类型保持和dao接口中函数的类型一致;