1、核心概念
2、Mybatis的使用模板
Mybatis固定的套路:
(1)、定义Xxxmap接口,定义对外sql的接口。
(2)、配置XxxMapper.xml文件,定义sql语句。
(3)、引入XxxMapper.xml文件,引入XxxMapper.xml文件进行解析。
(4)、调用Xxxmap接口,调用接口提供方法服务。
3、具体实现
1、新建一个com.mapper的包,定义map接口,这里以UserMapper为例
package com.mapper;
import java.util.List;
import com.pojo.User;
public interface UserMapper {
//根据用户id查询用户信息
public User findUserById(int id) throws Exception;
//查询用户列表
public List<User> findUserByUsername(String username) throws Exception;
//添加用户信息
public void insertUser(User user)throws Exception;
}
2、配置xml文件 UserMapper.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">
<!-- 注意这里的 namespace必须对应着map接口的全类名-->
<mapper namespace="com.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
<select id="findUserByUsername" parameterType="java.lang.String"
resultType="user">
select * from user where username like '%${value}%'
</select>
<insert id="insertUser" parameterType="user">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
</mapper>
3、在SqlMapConfig.xml中加入映射文件
<!-- 加载 映射文件 -->
<mappers>
<mapper resource="map/UserMapper.xml" />
</mappers>
4、调用方法
public static void main(String[] args) {
try {
// 基本mybatis环境
// 1.定义mybatis_config文件地址
String resources = "SqlMapConfig.xml";
// 2.获取InputStreamReaderIo流
Reader reader = Resources.getResourceAsReader(resources);
// 3.获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 4.获取Session
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取mapper接口的代理对象
UserMapper userMapper = session.getMapper(UserMapper.class);
//调用代理对象方法
User user = userMapper.findUserById(1);
System.out.println(user);
System.out.println("---------执行完毕-----------");
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭session
session.close();
}
}
感谢博主:
https://www.jianshu.com/p/a88e25193f25
https://www.douban.com/note/749318390/
https://blog.csdn.net/u013308490/article/details/85096879
https://blog.51cto.com/u_12222886/2052647
赞赞赞