共计 2196 个字符,预计需要花费 6 分钟才能阅读完成。
一、pom 文件
引入 mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、yml 配置
添加数据库配置和 mybatis 配置:
database.url=127.0.0.1:3306
spring.datasource.url=jdbc:mysql://${database.url}/demodb?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin123
mybatis.mapper-locations=classpath:mapper/*.xml
三、DAO
定义 DAO 接口,添加 @Mapper 注解:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.javashizhan.demo.mybatis.domain.User;
@Mapper
public interface UserDAO {User findUserByName(@Param(value = "name") String name) throws Exception;
void createUser(@Param(value = "user") User user) throws Exception;
int deleteUserByName(@Param(value = "name") String name) throws Exception;
}
四、mybatis 数据库脚本配置文件
脚本配置文件 User.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 命名空间应该是对应接口的包名 + 接口名 -->
<mapper namespace="com.javashizhan.demo.mybatis.dao.UserDAO">
<!-- id 值和 DAO 方法名保持一致,返回类型和 DAO 返回对象一致,字段别名和 User 字段名一致 -->
<select id="findUserByName" resultType="com.javashizhan.demo.mybatis.domain.User">
select
NAME name,
AGE age,
GENDER gender
from USER where name = #{name}
</select>
<insert id="createUser">
insert USER(
NAME,
AGE,
GENDER
) values(#{user.name},
#{user.age},
#{user.gender}
)
</insert>
<insert id="deleteUserByName">
delete from USER where name = #{name}
</insert>
</mapper>
将此文件放到 resources 目录的子目录 mapper 下,和 yml 配置文件中的路径一致。
五、Service 中调用 DAO
@Service
public class UserService {
@Autowired
private UserDAO userDAO;
public User findUserByName(@Param(value = "name") String name) throws Exception {return userDAO.findUserByName(name);
}
public void createUser(@Param(value = "user") User user) throws Exception {userDAO.createUser(user);
}
public int deleteUserByName(@Param(value = "name") String name) throws Exception {return userDAO.deleteUserByName(name);
}
}
以上为 spring 集成 mybatis 的所有步骤,完整实例代码扫码加入微信公众号并回复:<font color=”RED”>webfullstack</font>,获取仓库地址。
end.
站点:http://javashizhan.com/
微信公众号:
加入知识星球,参与讨论,更多实战代码分享!
https://t.zsxq.com/RNzfi2j
正文完