MyBatis
文章目录
log4j日志
添加依赖
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
编写配置文件
# 日志模块的配置
log4j.rootLogger=ERROR, stdout
# 打印级别
log4j.logger.site.leric.mybatis=DEBUG
# trace打印更多
#log4j.logger.site.leric.mybatis=TRACE
# 打印某个mapper 甚至单个方法的日志级别
log4j.logger.site.leric.mybatis.dao.VideoMapper.selectById=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
主函数
- Mybatis使⽤流程
- 创建mybatis-config.xml 全局的配置⽂件
- 创建XXXMapper.xml配置⽂件
- 创建SqlSessionFactory
- ⽤SqlSessionFactory创建SqlSession对象
- ⽤SqlSession执⾏增删改查CRUD
public class Main {
public static void main(String[] args) throws IOException {
// 读取配置文件
String resources = "config/mybatis-config.xml";
// 构建sessionFactory
InputStream inputStream = Resources.getResourceAsStream(resources);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取session
// 使用try方法获取会自动关闭
try(SqlSession session = factory.openSession()){
VideoMapper mapper = session.getMapper(VideoMapper.class);
Video video = mapper.selectById(36);
System.out.println(video.toString());
// 使用注解
// List<Video> videos = mapper.selectList();
List<Video> videos = mapper.selectListByXML();
for (Video video1 : videos) {
System.out.println(video1.toString());
}
}
}
配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 一个表会对应一个mapper,配置sql语句 -->
<mappers>
<!-- 注册mapper,被配置上的mapper会被自动扫描 -->
<mapper resource="mapper/VideoMapper.xml"/>
</mappers>
</configuration>
映射器
一个映射器由接口与mapper配置文件组成
public interface VideoMapper {
/**
* 根据视频id查找对象
* @param videoId
* @return
*/
// 使用注解给参数取别名 取了别名就要用别名
Video selectById(@Param("video_id") int videoId);
/**
* 查找全部视频成列表
* @return
*/
@Select("Select * from video") // 使用注解实现sql绑定
List<Video> selectList();
}
-
namespace:名称空间,一般保持全局唯一,最好能与dao曾的java接口一致,将自动关联相关方法
可以映射相关的sql语句到对应的方法和参数、返回类型
-
id:当前mapper下唯一,且需要与接口方法一致方便封装
-
resultType:sql查询结果集的封装对象
<mapper namespace="site.leric.mybatis.dao.VideoMapper"> <select id="selectById" resultType="site.leric.mybatis.domain.Video"> select * from video where id = #{video_id} </select> </mapper>
传参与入参
-
在接口的方法里使用@Param为参数指定别名
-
配置问文件SQL语句使用#{ } 或者 ${ } 引用参数
-
推荐使用#{ } ,因为${ } 实际上是拼接SQL命令,有面临QL注入的风险
<mapper namespace="site.leric.mybatis.dao.VideoMapper">
<select id="selectById" resultType="site.leric.mybatis.domain.Video">
select * from video where id = #{video_id}
</select>
<select id="selectListByXML" resultType="site.leric.mybatis.domain.Video">
select * from video
</select>
</mapper>
简单查询
Select语句
- 根据id查询一条记录
<!-- 参数类型并不需要过多的关注,MyBatis可以自动转化 -->
<!-- jdbcType 用于指定传入数据库的参数的转换类型,通常来说是需要手动指定,否则会出现无效类型错误 -->
<select id="selectById" parameterType="java.lang.Integer" resultType="site.leric.mybatis.domain.Video">
select * from video where id = #{videoid,jdbcType=INTEGER}
</select>
-
使用paramaterType指定自定义参数类型
在select语句中若传入自定义对象作为参数,需要取得封装类的字段作为参数,在sql语句中需要pojo.field
<!-- 传参为自定义对象,入参时需要POJO.filed -->
<select id="selectByPointAndTitleLikeOnVideo" parameterType="site.leric.mybatis.domain.Video" resultType="site.leric.mybatis.domain.Video">
select * from video where point = #{video.point} and title like concat('%',#{video.title},'%')
</select>
-
模糊查询
模糊查询不能使用字符串拼接,需要使用自带函数concat(‘%’,paramater,‘%’)
<!-- 模糊查询不能使用'%%' 字符串拼接的方式 -->
<select id="selectByPointAndTitleLike" resultType="site.leric.mybatis.domain.Video">
select * from video where point = #{point} and title like concat('%',title,'%')
</select>
- sql片段复用
<mapper namespace="site.leric.mybatis.dao.VideoMapper">
<!-- 定义sql片段 -->
<sql id="base_select" >
id,summary,title
</sql>
<!-- 配置了别名之后使用别名 -->
<select id="selectById" resultType="video">
<!-- 复用sql片段 -->
select <include refid="base_select"/> from video where id = #{video_id}
</select>
</mapper>
insert语句
-
插入一条数据并回填主键
插入数据若参数类型是自定义的自定义对象,则入参是只需要调用封装对象的属性名即可
<!-- 插入记录 useGeneratedKeys="true" 主键回填 keyProperty="id" 映射Java对象属性 keyColumn="id" 映射数据库字段 当参数非集合的时候,MyBatis能自动识别字段 --> <insert id="add" parameterType="site.leric.mybatis.domain.Video" useGeneratedKeys="true