一、配置环境
第一次跑主要分为以下五个步骤、 其中涉及的文件
1、pom.xml 这是添加依赖的文件。相当于 flutter 的 yaml OC 的 podfile
2、mybais-config.xml 这个是mybaits 的配置文件。里面需要配置用户名密码、和映射文件
3、UserMapper.xml 这个是你需要写具体sql的地方。
4、User java class 这是你的映射对象。
5、UserMapper java interface 这是你的映射接口
1、添加 mybatis 依赖、和 mysql 相关依赖
在 pom.xml 里面添加依赖。
<?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>org.example</groupId>
<artifactId>TestMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
2、添加 mybatis 配置文件 mybatis-config.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>
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<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"/>
<property name="username" value="admin"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="UserMapper.xml"/>
<!-- <mapper resource="com/itheima/mapper/UserMapper.xml"/>-->
<!--Mapper代理方式-->
<!-- <package name="com.itheima.mapper"/>-->
</mappers>
</configuration>
3、创建 映射文件、例如UserMapper.xml 并且在 mybatis-config.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">
<!--
namespace:名称空间
-->
<mapper namespace="user">
<select id="selectAll" resultType="com.login.User">
select *
from tb_user;
</select>
<!-- <select id="selectById" resultType="user">-->
<!-- select *-->
<!-- from tb_user where id = #{id};-->
<!-- </select>-->
</mapper>
4、创建 User 类、 添加相关属性。 实现 set get tostring 方法
package com.login;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class User {
// alt + insert 可以添加 get set 方法
// lombok 可以快捷添加
protected int id;
protected String username;
protected String password;
protected String gender;
protected String addr;
}
5、开始创建测试 实例。
package com.login;
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;
public class Appdelegate {
public static void main(String[] args) throws IOException {
// 加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 session对象。
SqlSession sqlSession = factory.openSession();
// 执行sql
List<User> users = sqlSession.selectList("user.selectAll");
System.out.println(users);
sqlSession.close();
}
}
一、基础学习
1、代理映射
1、创建 UserMapper 接口文件和 UserMapper.xml 分别在不同文件夹同一个目录下面。如图
注意: UserMapper 使用 new package 创建 录入 com.jince.mapper 即可 但是 UserMapper.xml 的目录 使用 new Directory 创建、且录入使用com/jince/mapper录入
2、编写接口
package com.jince.mapper;
import com.jince.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
}
3、修改 UserMapper.xml 映射
<mapper namespace="com.jince.mapper.UserMapper">
<select id="selectAll" resultType="com.jince.User">
select *
from tb_user;
</select>
</mapper>
4、修改 config 映射路径
<mappers>
<!--加载sql映射文件-->
<mapper resource="com/jince/mapper/UserMapper.xml"/>
</mappers>
为了方便不要每次都重新编写 config文件。 映射文件可以改为检索的方式
<mappers>
<!--加载sql映射文件-->
<!-- <mapper resource="com/jince/mapper"/>-->
<!--使用Mapper 检索-->
<package name="com.jince.mapper"/>
</mappers>
2、起别名
- 在config里面增加别名配置。
- 在返回值中直接使用别名
3、修改数据库返回字段
- 使用别名的方式、就和数据库查询的时候、给表明起别名一样。
- 使用resultMap 方式
4、参数查询
- 传递参数
<select id="selectById" resultMap="barndResultMap">
select * from tb_brand where id = #{id};
</select>
参数使用 #{} 传递、或者使用 ${} 传递 推荐使用 #{} 因为他没有sql注入问题
- 特殊字符
<!-- <select id="selectBrandWhereBigId" resultMap="barndResultMap">-->
<!-- select * from tb_brand where id < #{id};-->
<!-- </select>-->
<select id="selectBrandWhereBigId" resultMap="barndResultMap">
select * from tb_brand
where
id <![CDATA[
<
]]> #{id};
</select>
特殊字符使用占位符。 或者 CDATA处理
5、条件查询
多条件查询
一、散装参数
public List<Brand> selectByBrand(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);
<select id="selectByBrand" resultMap="barndResultMap">
select * from tb_brand
where
status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName};
</select>
public static void testSelect(int status, String companyName, String brandName) throws IOException {
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
// 加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 session对象。
SqlSession sqlSession = factory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectByBrand(status,companyName,brandName);
System.out.println(brands);
sqlSession.close();
}
二、封装对象
// Brand brand = new Brand();
// brand.setStatus(status);
// brand.setBrandName(brandName);
// brand.setCompanyName(companyName);
// List<Brand> brands = mapper.selectByBrand(brand);
// System.out.println(brands);
public List<Brand> selectByBrand(Brand brand);
三、封装成 map
public List<Brand> selectByBrand(Map brand);
HashMap params = new HashMap();
params.put("status", status);
params.put("brandName", brandName);
params.put("companyName", companyName);
List<Brand> brands = mapper.selectByBrand(params);
System.out.println(brands);
6、动态条件查询
<select id="selectByBrand" resultMap="barndResultMap">
select * from tb_brand
where 1 = 1
<if test="status != null">
and 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>
</select>
或者不用恒等式、使用where帮where标签包裹起来
7、添加
注意事务 主键返回
public void addBrand(Brand brand);
<insert id="addBrand" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name, company_name, ordered, description)
values (#{brandName}, #{companyName}, #{ordered}, #{description})
</insert>
// 获取 session对象。
SqlSession sqlSession = factory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setDescription(des);
brand.setOrdered(300);
mapper.addBrand(brand);
System.out.println(brand.getId());
8、修改
动态修改、修改全部
public static void update(int status, String companyName, String brandName, String des) throws IOException {
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
// 加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 session对象。
SqlSession sqlSession = factory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setDescription(des);
brand.setOrdered(300);
brand.setId(3);
mapper.updateBrand(brand);
sqlSession.close();
}
public void updateBrand(Brand brand);
<!-- <update id="updateBrand">-->
<!-- update tb_brand-->
<!-- set-->
<!-- company_name = #{companyName},-->
<!-- description = #{description}-->
<!-- where id = #{id};-->
<!-- </update>-->
<update id="updateBrand">
update tb_brand
<set>
<if test="companyName != null and companyName != '' ">
company_name = #{companyName},
</if>
<if test="description != null and description != '' ">
description = #{description},
</if>
</set>
where id = #{id};
</update>
9、删除
传array 默认会转化成 map 、使用array 作为key取值。 获取增加 @Param 解注释
public static void testDele() throws IOException {
// 加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 session对象。
SqlSession sqlSession = factory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
int[] array = new int[] {5, 6};
mapper.deleteByList(array);
sqlSession.close();
}
@Delete("delete from tb_brand where id = #{id}")
public void deleteById(@Param("id") int id);
public void deleteByList(@Param("ids") int[] ids);
<delete id="deleteByList">
delete from tb_brand where id
in
<foreach open="(" close=")" collection="ids" item="id" separator=",">
#{id}
</foreach>
</delete>