1. MyBatis开发步骤
MyBatis官网地址:http://www.mybatis.org/mybatis-3/
案例需求:通过 mybatis 查询数据库 user 表的所有记录,封装到 User 对象中,打印到控制台上步骤分析: 1. 创建数据库及 user 表 2. 创建 maven 工程,导入依赖( MySQL 驱动、 mybatis 、 junit ) 3. 编写 User 实体类 4. 编写 UserMapper.xml 映射配置文件( ORM 思想) 5. 编写 SqlMapConfig.xml 核心配置文件 数据库环境配置 映射关系配置的引入 ( 引入映射配置文件的路径 ) 6. 编写测试代码 //1. 加载核心配置文件 //2. 获取 sqlSessionFactory 工厂对象 //3. 获取 sqlSession 会话对象 //4. 执行 sql //5. 打印结果 //6. 释放资源2. 代码实现
1) 创建user数据表
CREATE DATABASE `mybatis_db`;
USE `mybatis_db`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT'用户名称',
`birthday` datetime default NULL COMMENT'生日',
`sex` char(1) default NULL COMMENT'性别',
`address` varchar(256) default NULL COMMENT'地址',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
--insert....
insert into`user`(`id`,`username`,`birthday`,`sex`,`address`)values(1,'子慕','2020-11-1100:00:00','男','北京海淀'),(2,'应颠','2020-12-1200:00:00','男','北京海淀');
2) 导入MyBatis的坐标和其他相关坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lagou</groupId>
<artifactId>mybatis_dao</artifactId>
<version>1.0-SNAPSHOT</version>
<!--指定编码及版本-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.11</java.version>
<maven.compiler.source>1.11</maven.compiler.source>
<maven.compiler.target>1.11</maven.compiler.target>
</properties>
<!--引入相关依赖-->
<dependencies>
<!--引入mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--引入mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--引入junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 分页助手 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
</project>
3) 编写User实体
package com.lagou.domain;
import java.util.Date;
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
4) 编写UserMapper映射文件
<?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.lagou.mapper.UserMapper">
<!--根据id查询用户-->
<select id="findUserById" parameterType="int" resultMap="userResultMap">
select * from user where id = #{id}
</select>
<!--id : 标签的唯一标识
type: 封装后实体类型-->
<resultMap id="userResultMap" type="com.lagou.domain.User">
<!--手动配置映射关系-->
<!--id: 用来配置主键-->
<id property="id" column="id"></id>
<!-- result: 表中普通字段的封装-->
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</resultMap>
<!--查询所有用户-->
<!--resultMap:手动配置实体属性与表中字段的映射关系,完成手动封装-->
<select id="findAllResultMap" resultMap="userResultMap">
select * from user
</select>
<!--多条件查询:方式一-->
<select id="findByIdAndUsername1" resultMap="userResultMap" >
<!-- select * from user where id = #{arg0} and username = #{arg1}-->
select * from user where id = #{param1} and username = #{param2}
</select>
<!--多条件查询:方式二-->
<select id="findByIdAndUsername2" resultMap="userResultMap" >
select * from user where id = #{id} and username = #{username}
</select>
<!--多条件查询:方式三-->
<select id="findByIdAndUsername3" resultMap="userResultMap" parameterType="com.lagou.domain.User">
select * from user where id = #{id} and username = #{usernameabc}
</select>
<!--模糊查询:方式一-->
<select id="findByUsername" resultMap="userResultMap" parameterType="string">
<!-- #{}在mybatis中是占位符,引用参数值的时候会自动添加单引号 -->
select * from user where username like #{username}
</select>
<!--模糊查询:方式二-->
<select id="findByUsername2" resultMap="userResultMap" parameterType="string">
<!--parameterType是基本数据类型或者String的时候,${}里面的值只能写value
${}: sql原样拼接
-->
select * from user where username like '${value}'
</select>
<!--添加用户:获取返回主键:方式一-->
<!--
useGeneratedKeys: 声明返回主键
keyProperty:把返回主键的值,封装到实体中的那个属性上
-->
<insert id="saveUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
<!--添加用户:获取返回主键:方式二-->
<insert id="saveUser2" parameterType="user" >
<!--
selectKey : 适用范围更广,支持所有类型的数据库
order="AFTER" : 设置在sql语句执行前(后),执行此语句
keyColumn="id" : 指定主键对应列名
keyProperty="id":把返回主键的值,封装到实体中的那个属性上
resultType="int":指定主键类型
-->
<selectKey order="AFTER" keyColumn="id" keyProperty="id" resultType="int">
SELECT LAST_INSERT_ID();
</selectKey>
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 动态sql之if : 多条件查询-->
<select id="findByIdAndUsernameIf" parameterType="user" resultType="com.lagou.domain.User">
select * from user
<!-- test里面写的就是表达式
<where>: 相当于where 1= 1,但是如果没有条件的话,不会拼接上where关键字
-->
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="username !=null">
and username = #{username}
</if>
</where>
</select>
<!--动态sql之set : 动态更新-->
<update id="updateIf" parameterType="user">
update user
<!--<set> : 在更新的时候,会自动添加set关键字,还会去掉最后一个条件的逗号 -->
<set>
<if test="username != null">
username = #{username},
</if>
<if test="birthday != null">
birthday = #{birthday},
</if>
<if test="sex != null">
sex = #{sex},
</if>
<if test="address != null">
address = #{address},
</if>
</set>
where id = #{id}
</update>
<sql id="selectUser">
select * from user
</sql>
<!--动态sql的foreach标签:多值查询:根据多个id值查询用户-->
<select id="findByList" parameterType="list" resultType="user">
<include refid="selectUser"/>
<where>
<!--
collection : 代表要遍历的集合元素,通常写collection或者list
open : 代表语句的开始部分
close : 代表语句的结束部分
item : 代表遍历结合中的每个元素,生成的变量名
separator: 分隔符
-->
<foreach collection="collection" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
<!--动态sql的foreach标签:多值查询:根据多个id值查询用户-->
<select id="findByArray" parameterType="int" resultType="user">
<include refid="selectUser"/>
<where>
<!--
collection : 代表要遍历的集合元素,通常写collection或者list
open : 代表语句的开始部分
close : 代表语句的结束部分
item : 代表遍历结合中的每个元素,生成的变量名
separator: 分隔符
-->
<foreach collection="array" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
5) 编写MyBatis核心文件
<?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>
<!--加载properties文件-->
<properties resource="jdbc.properties"></properties>
<!--设置别名-->
<typeAliases>
<!--方式一:给单个实体起别名-->
<!-- <typeAlias type="com.lagou.domain.User" alias="user"></typeAlias>-->
<!--方式二:批量起别名 别名就是类名,且不区分大小写-->
<package name="com.lagou.domain"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!--dialect: 指定方言 limit-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
<!--environments: 运行环境-->
<environments default="development">
<environment id="development">
<!--当前的事务事务管理器是JDBC-->
<transactionManager type="JDBC"></transactionManager>
<!--数据源信息 POOLED:使用mybatis的连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
<!--<mapper resource="com/lagou/mapper/UserMapper.xml"></mapper>-->
<!--使用该方式:接口和映射文件需要同包同名-->
<!-- <mapper class="com.lagou.mapper.UserMapper"></mapper>-->
<!--批量加载映射-->
<package name="com.lagou.mapper"/>
</mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis_db?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
6) 编写测试类
@Test
public void mybatisQuickStart() throws IOException {
//1.加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//2. 获取sqlSessionFactory工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//3. 获取sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4. 执行sql 参数:statementid : namespace.id
List<User> users = sqlSession.selectList("userMapper.findAll");
//5. 遍历打印结果
for (User user : users) {
System.out.println(user);
}
//6. 关闭资源
sqlSession.close();
}