pom.xml
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>mybatis-demoartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.21version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.3version>
dependency>
dependencies>
project>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="xxxx"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
logback.xml
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %npattern>
encoder>
appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
logger>
<root level="DEBUG">
<appender-ref ref="Console"/>
root>
configuration>
UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_user;
select>
mapper>
MyBatisDemo
package com.itheima;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static java.lang.System.out;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 1.加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取sqlSession对象,执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.执行sql
List<User> users = sqlSession.selectList("test.selectAll");
out.println(users);
// 4.释放资源
sqlSession.close();
}
}
我们上面的代码中还是有一些例如test.selectAll
的硬编码,这样对于后期的维护还是不方便的,因此我们使用代理
代理开发的规则:
如果Mapper接口名称和SQL映射文件名相同,并且在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载
Mybatis配置参数
要思考以下几点:
// 创建Mapper文件
package com.itheima.mapper;
import com.itheima.pojo.Brand;
import java.util.List;
public interface BrandMapper {
/**
* 查询所有
*/
public List<Brand> selectAll();
}
// 配置BrandMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
<select id="selectAll" resultType="com.itheima.pojo.Brand">
select * from tb_brand;
</select>
</mapper>
// 在mybatis-config.xml添加sql映射
<mapper resource="com/itheima/mapper/BrandMapper.xml"/>
// 编写测试文件
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
// 1.获取sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 4.执行方法
List<Brand> brands = brandMapper.selectAll();
out.println(brands);
// 5.释放资源
sqlSession.close();
}
}
Brand类中使用的是驼峰命名,而数据库中是下划线命名,此时会导致找不到数据,我们可以使用
方法一:别名+sql片段
<sql id="brand_column">
id,brand_name as brandName,company_name as companyName,ordered,description,status
</sql>
<select id="selectAll" resultType="com.itheima.pojo.Brand">
select
<include refid="brand_column"></include>
from tb_brand;
</select>
方法二:resultMap
<resultMap id="brandResultMap" type="com.itheima.pojo.Brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select
*
from tb_brand;
</select>
// BrandMapper
Brand selectById(int id);
// BrandMapper.xml
<!-- 参数占位符:
1.#{}:会替换参数为?,防止sql注入
2.${}:会显示参数-->
<!--如果有特殊字符,有两种解决办法
1.转义(同前端代码)
2.CDATA区内写-->
<select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id = #{id};
</select>
// 测试
Brand brand = brandMapper.selectById(id);
out.println(brand);
// BrandMapper.xml
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand where
status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName};
</select>
// BrandMapper.java
/** 1.散装参数:如果方法中有多个参数,需使用@Param("SQL参数占位符名称")
* 2.对象参数:对象的属性名称要和参数占位符名称一致
* 3.map集合参数:SQL中的参数名和map集合的键的名称对应
*/
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);
List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map map);
上面的多条件查询有bug,当用于输入的条件不全时,查不到信息,这显然是不符合常理的,因此我们要进行动态查询
动态查询的原理是:SQL语句会随着用户的输入或外部调价的变化而变化,即动态SQL
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
<where>
<if test="status != null">
status = #{status}
if>
<if test="companyName != null and companyName != ''">
and company_name like #{companyName}
if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName};
if>
where>
select>
mybatis提供了choose(when,otherwise)
,类似与switch语句
在数据添加成功后,有时需要获取插入数据库数据的主键,此时的id是没有绑定到对象上的,我们可以使用
<insert id="add" useGeneratedKeys="true" keyProperty="id">
实现主键返回
例如修改密码的功能,我们通常只会修改一条数据的部分字段
实现方式就是加一些判断
同样,在更新数据的时候也会遇到mysql代码多,
,或者一条数据都没改的情况。这样执行mysql会报错,mybatis为我们提供了
来解决这个问题
mybatis提供了
标签来进行数组的遍历
<foreach collection="array">foreach>
@Param
void deleteByIds(@Param("ids") int[] ids);
separator
参数为分隔符,open
为foreach开始前的符号,close
为foreach结束后的符号
将SQL语句写在注解里