
什么是Mybatis
- mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
- mybatis通过xml或注解的方式将要执行的各种statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。
- 最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc进行了封装,屏蔽了jdbc api底层访问细节,使我们不用与jdbc api打交道,就可以完成对数据库的持久化操作。
Mybatis入门
Mybatis开发步骤:
1.添加Maven依赖 2.写mybatis-config.xml配置文件 3.写实体类 4.写Mapper接口 5.写XML映射文件 6.写测试类
第一个Mybatis程序
环境搭建
1.建库建表
CREATE DATABASE `mybatis`;DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` int(20) NOT NULL AUTO_INCREMENT,`name` varchar(30) DEFAULT NULL,`pwd` varchar(30) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `user` VALUES ('1', '张三', '123456');INSERT INTO `user` VALUES ('2', '李四', '654321');INSERT INTO `user` VALUES ('3', '王二麻子', '111111');
创建Java项目
1.新建一个普通的maven项目
2.添加maven依赖
<dependencies>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- juit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3.XML 配置文件
<?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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
4.写User实体类
@Data
public class User {
private Integer id;
private String name;
private String pwd;
}
5.写Mapper接口
public interface UserMapper {
List<User> getAllUser();
}
6.写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.jokey.dao.UserMapper">
<select id="getAllUser" resultType="com.jokey.entity.User">
select * from user
</select>
</mapper>
7.写测试类
public class MybatisTest {
public static void main(String[] args) throws IOException {
// 1.获得核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.构建 SqlSessionFactory
// SqlSessionFactory 的实例可以从 XML 配置文件来构建出
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.既然有了 SqlSessionFactory ,顾名思义,可以从中获得 SqlSession 的实例
// SqlSession 提供了在数据库执行sql命令所需的所有方法
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4.获得Mapper执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> allUser = mapper.getAllUser();
System.out.println(allUser);
// 5.释放资源
sqlSession.close();
}
}
Mybatis配置文件
XML映射文件
select、insert、update和delete
| 属性 | 描述 |
|---|---|
| id | 对应Mapper接口中的方法名 |
| parameterType | 参数类型,填全限定名或别名,写或不写均可,MyBatis可以推断出传入参数的类型 |
| resultType | 返回结果类型,如果返回的是集合,应设置为集合包含的类型,不是集合的类型 |
| resultMap | 结果映射 |
不同参数类型
- 基本参数类型(参数少时使用,搭配@Param注解)
int addUser(@Param("id") Integer id, @Param("name") String name, @Param("pwd") String pwd);
<insert id="addUser">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
对象类型(参数4个或是4个以上时,建议使用对象封装)
int insertUser(User user);传递的参数是对象类型时,会根据对象的属性名来查找对应的参数,然后将值传入预处理语句的参数中
<insert id="insertUser" parameterType="com.jokey.entity.User"> insert into user (id,name,age,email,pwd) values (#{id},#{name},#{age},#{email},#{pwd}) </insert>集合类型
一些需要注意的地方:
- sql语句不用写分号,参考官方文档中没写
- 模糊查询推荐写法
select * from user where name like CONCAT('%',#{para},'%')
Mybatis 注解开发
Mybatis 动态SQL
- 使用
where和if标签拼接查询条件<select id="queryUser" parameterType="com.jokey.entity.User" resultType="java.lang.Integer"> select count(id) from user <where> <if test="username !=null and username !='' "> u.username = #{username} </if> <if test="userNo !=null and userNo !='' "> AND u.user_no = #{userNo} </if> </where> </select>
使用记录
1.mybatis list条件判断
<if test="userIds != null and userIds.size > 0">
AND user_id in
<foreach collection="userIds" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</if>
2.mybatis 批量模糊查询
<if test="meterNames != null and meterNames.size > 0">
AND
<foreach collection="meterNames" item="meterName" open="(" separator="OR" close=")">
m.name LIKE CONCAT('%',#{meterName},'%')
</foreach>
</if>
