目录
一、引入依赖
二、配置数据库的连接信息
三、实现持久层代码
3.1 添加mapper接口
3.2 添加UserInfoXMLMapper.xml
3.3 增删改查操作
3.3.1 增(insert)
3.3.2 删(delete)
3.3.3 改(update)
3.3.4 查(select)
本篇内容仍然衔接上篇内容,使用的代码及案例仍是上篇的内容,MyBatis的基础操作。上篇是采用注解的方式实现CRUD,本篇介绍XML的方式。
MyBatis的开发有两种方式:注解和XML,使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,可使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。
一、引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
二、配置数据库的连接信息
如果是yml文件:
# 数据库连接配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 配置 mybatis xml 的文件路径,在 resources/mapper 创建所有表的 xml 文件
mybatis:
mapper-locations: classpath:mapper/**Mapper.xml
如果是properties文件:
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=root
# 配置 mybatis xml 的文件路径,在 resources/mapper 创建所有表的 xml 文件
mybatis.mapper-locations=classpath:mapper/**Mapper.xml
三、实现持久层代码
持久层代码分为两部分:
- 方法定义:interface
- 方法实现:×××.xml
3.1 添加mapper接口
import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserInfoXMlMapper {
List<UserInfo> queryAllUser();
}
3.2 添加UserInfoXMLMapper.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.example.demo.mapper.UserInfoMapper">
</mapper>
UserInfoXMLMapper.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.example.mybatis_demo.mapper.UserInfoXMLMapper">
<select id="queryAllUser" resultType="com.example.mybatis_demo.model.UserInfo">
select username,`password`, age, gender, phone from userinfo
</select>
</mapper>
测试代码:
@SpringBootTest
class UserInfoXMLMapperTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void queryAllUser() {
userInfoMapper.queryUserInfos().forEach(System.out::println);
}
}
运行代码:
3.3 增删改查操作
3.3.1 增(insert)
Integer insertUser(UserInfo userInfo);
<insert id="insertUser">
insert into userinfo (username, `password`, age, gender, phone) values (#{username}, #{password}, #{age},#{gender},#{phone})
</insert>
如果使用@Param设置参数名称的话,使用方法和注解类似。
Integer insertUser(@Param("userinfo") UserInfo userInfo);
<insert id="insertUser">
insert into userinfo (username, `password`, age, gender, phone) values
(#{userinfo.username},#{userinfo.password},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})
</insert>
返回自增 id:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into userinfo (username, `password`, age, gender, phone) values
(#{userinfo.username},#{userinfo.password},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})
</insert>
3.3.2 删(delete)
Integer deleteUser(UserInfo userInfo);
<delete id="deleteUser">
delete from userinfo where id=#{id}
</delete>
3.3.3 改(update)
Integer updateUser(UserInfo userInfo);
<update id="updateUser">
update userinfo set username=#{username} where id=#{id}
</update>
3.3.4 查(select)
我们在上面查询时发现, 有几个字段是没有赋值的,只有Java对象属性和数据库字段一模一样时, 才会进行赋值。
如果将上述没有查询的数据进行查询:
<select id="queryAllUser" resultType="com.example.mybatis_demo.model.UserInfo">
select username,`password`, age, gender, phone, delete_flag, create_time, update_time from userinfo
</select>
结果:
从运行结果上可以看到,SQL语句中, 查询了delete_flag, create_time, update_time,但是这几个属性却没有赋值.
解决办法和注解相似:
- 起别名
- 结果映射
- 开启驼峰命名
其中方法1和3跟注解一样,那么这儿就介绍结果映射,使用xml来写:
Mapper.xml
<resultMap id="BaseMap" type="com.example.demo.model.UserInfo">
<id column="id" property="id"></id>
<result column="delete_flag" property="deleteFlag"></result>
<result column="create_time" property="createTime"></result>
<result column="update_time" property="updateTime"></result>
</resultMap>
<select id="queryAllUser" resultMap="BaseMap">
select id, username,`password`, age, gender, phone, delete_flag, create_time, update_time from userinfo
</select>
3.4 多表查询
数据准备:
-- 创建⽂章表
DROP TABLE IF EXISTS articleinfo;
CREATE TABLE articleinfo (
id INT PRIMARY KEY auto_increment,
title VARCHAR ( 100 ) NOT NULL,
content TEXT NOT NULL,
uid INT NOT NULL,
delete_flag TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
create_time DATETIME DEFAULT now(),
update_time DATETIME DEFAULT now()
) DEFAULT charset 'utf8mb4';
-- 插⼊测试数据
INSERT INTO articleinfo ( title, content, uid ) VALUES ( 'Java', 'Java正⽂', 1
);
import lombok.Data;
import java.util.Date;
@Data
public class ArticleInfo {
private Integer id;
private String title;
private String content;
private Integer uid;
private Integer deleteFlag;
private Date createTime;
private Date updateTime;
}
select
ta.id,
ta.title,
ta.content,
ta.uid,
tb.username,
tb.age,
tb.gender
FROM
articleinfo ta
LEFT JOIN userinfo tb ON ta.uid = tb.id
WHERE
ta.id =1
@Data
public class ArticleInfo {
private Integer id;
private String title;
private String content;
private Integer uid;
private Integer deleteFlag;
private Date createTime;
private Date updateTime;
//用户相关信息
private String username;
private Integer age;
private Integer gender;
}
import com.example.demo.model.ArticleInfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArticleInfoMapper {
@Select("SELECT
ta.id,ta.title,ta.content,ta.uid,tb.username,tb.age,tb.gender " +
"FROM articleinfo ta LEFT JOIN userinfo tb ON ta.uid = tb.id " +
"WHERE ta.id = #{id}")
ArticleInfo queryUserByUid(Integer id);
}