2.类型别名(typeAiases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:
当这样配置时,Blog 可以用在任何使用 domain.blog.Blog 的地方。
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
上面的resultType直接省略了包名
- 注:配置别名的时候需要注意顺序
在IDEA的file-setting-plugins中搜索mybatisx,然后安装即可,可能需要适当重启IDEA
红色小鸟是映射文件,蓝色是Mapper接口,点击可以直接跳转
作用:
①如在映射文件中写上sql语句,点击后可以直接跳转到mapper接口方法中去
②在mapper中写好接口方法可以自动生成statement的标签
2.数据库表tb_brand.sql-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1);
SELECT * FROM tb_brand;
3.实体类Brand.java
package com.itheima.pojo;
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + ''' +
", companyName='" + companyName + ''' +
", ordered=" + ordered +
", description='" + description + ''' +
", status=" + status +
'}';
}
}
4.测试用例
在test/java目录下创建com.itheima.test包,在包下创建一个测试类MyBatisTest.java,这只是环境准备。
增删改查 1.练习查询所有数据 1.编写接口方法Mapper接口- 参数:无
- 结果:List
List
①在mapper包下创建BrandMapper接口
package com.itheima.mapper;
import com.itheima.pojo.Brand;
import java.util.List;
public interface BrandMapper {
List selectAll();
}
2.编写SQL语句:SQL映射文件
①在resources目录的mapper下创建映射文件:BrandMapper.xml,回到BrandMapper接口,创建statement
,然后书写sql语句
3.执行方法:测试
在MyBatisTest中书写代码:
(在spring整合后只需要写 List
package com.itheima.test;
import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 brands = brandMapper.selectAll();
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
}
总结:MyBatis完成操作的步骤:
三步:编写接口方法–>编写SQL语句–>执行方法
4.相关问题的解决 数据库表的字段名称和实体类的属性名称不一样,则不能自动封住数据解决方案一:
起别名,让别名和实体类的属性名一样,缺点是每次查询都要定义一次别名
sql片段:
id,brand_name as brandName,company_name as companyName,ordered,description,status
解决方案二:
ResultMap
2.练习通过id查询
1.编写接口方法:Mapper接口
- 参数:id
- 结果:Brand
3.执行方法测试
略
3.条件查询 1.多条件查询1.编写接口方法
- 参数:所有查询条件
- 结果:List
// ListselectByCondition(@Param("status") int status,@Param("companyName")String companyName,@Param("brandName")String brandName); // List selectByCondition(Brand brand); List selectByCondition(Map map);
2.编写SQL语句:SQL映射文件
3.执行方法,测试
@Test
public void testSelectByCondition() throws IOException {
//接受参数
int status=1;
String companyName="华为";
String brandName="华为";
//处理参数
companyName="%"+companyName+"%";
brandName="%"+brandName+"%";
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
//封装map集合
Map map = new HashMap();
map.put("status",status);
map.put("companyName",companyName);
map.put("brandName",brandName);
//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 brands = brandMapper.selectByCondition(map);
// List brands = brandMapper.selectByCondition(status, companyName, brandName);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
相关问题:
如果某一个条件为空,就会出现问题
4.动态条件查询(多条件)1.SQL语句会随着用户的输入或外部条件的变化而变化,我们称之为动态SQL
2.MyBatis对动态SQL的支撑:
- if–
使用where标签:
# where,这里的where需要注释掉
# 1 = 1
and status=#{status}
# 这里写属性值而不是数据库里面的字段
and company_name like #{companyName}
and brand_name like #{brandName}
5.单条件动态条件查询
- choose(when,otherwise)
6.添加
1.添加方法
void add(Brand brand);
2.SQL映射
insert into tb_brand(brand_name, company_name, ordered, description, status)
values(#{brandName},#{brandName},#{ordered},#{description},#{status})
3.测试方法(注意提交事务)
@Test
public void testAdd() throws IOException {
//接受参数
int status=1;
String companyName="波导手机";
String brandName="波导";
String description = "手机中的战斗机";
int orderd=100;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(orderd);
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.add(brand);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
- 添加–主键返回
1.修改映射,添加两个属性useGenerateKeys和keyProperty
insert into tb_brand(brand_name, company_name, ordered, description, status)
values(#{brandName},#{brandName},#{ordered},#{description},#{status})
2.在测试方法提交后可以获取到id属性
//4.执行方法
brandMapper.add(brand);
System.out.println(brand.getId());
7.修改
- 修改全部字段
1.编写接口方法:Mapper接口
参数:所有数据
结果:void
int update(Brand brand);
2.编写SQL语句:SQL映射文件
update tb_brand
set brand_name=#{brandName},
company_name=#{companyName},
ordered=#{ordered},
description=#{description},
status=#{status}
where id=#{id};
3.执行方法:测试
@Test
public void testupdate() throws IOException {
//接受参数
int status=1;
String companyName="波导手机";
String brandName="波导";
String description = "波导手机,手机中的战斗机";
int orderd=200;
int id=7;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(orderd);
brand.setId(id);
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
int count = brandMapper.update(brand);
System.out.println(count);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
- 修改动态字段–修改部分字段(如:只需要修改密码)
1.编写接口方法:Mapper接口
参数:部分数据,封装到对象中
结果:void/int
2.编写SQL语句:SQL映射文件
主要是标签和标签的使用
update tb_brand
brand_name=#{brandName},
company_name=#{companyName},
ordered=#{ordered},
description=#{description},
status=#{status}
where id=#{id};
3.执行方法:测试
tips:Ctrl+Alt+L格式化代码
8.删除- 删除单个
1.编写接口方法:Mapper接口
参数:id
结果:void/int
void deleteById(Brand brand);
2.编写SQL语句:SQL映射文件
delete from tb_brand where id=#{id}
3.执行方法,测试
@Test
public void testdeleteById() throws IOException {
//接受参数
int id=6;
//封装对象
Brand brand = new Brand();
brand.setId(id);
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteById(brand);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
- 批量删除
1.编写接口方法:Mapper接口
参数:id数组
结果:void
void deleteByIds(@Param("ids") int[] ids);
2.编写SQL语句:SQL映射文件
delete from tb_brand where id in
#{id}
3.执行方法:测试
@Test
public void testdeleteByIds() throws IOException {
//接受参数
int[] ids = {5, 7};
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteByIds(ids);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
参数传递
1.在UserMapper中写下以下方法(知识点在注释里面)
User select(@Param("username") String username, @Param("password") String password);
User select(Collection collection);
2.写相应映射
3.测试方法
@Test
public void testselect() throws IOException {
//接受参数
String username="admin";
String password="admin";
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//4.执行方法
// User user = userMapper.select(username, password);
User user = userMapper.select(new HashSet());
System.out.println(user);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
-
相关知识点解读,在源码中查看相应操作:
①在IDEA中快速点击两下Shift键进入搜索,搜索ParamNameResolver.class文件,注意要搜索文件,没有源码需要下载源码
②找到getNamedParams方法,在第一行加断点
③调试测试方法,细品里面的方法,通过步入进入下一步,查看变量
④里面有个wrapToMapCollection方法需要注意,Ctrl+鼠标左键点进去后在第一行添加断点
注解开发官网解释:
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。
所以,注解可以完成简单开发,XML适合复杂一点的开发
1.注解开发不要写xml文件,所以通过在Mapper接口中点击小红鸟把UserMapper.xml文件中相应方法selectById注释掉
2.在UserMapper方法中添加注解
@Select("select * from t_user where id=#{id}")
User selectById(int id);
3.测试方法
@Test
public void testselectById() 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();
// 开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//4.执行方法
User user = userMapper.selectById(1);
System.out.println(user);
//手动提交事务
// sqlSession.commit();
//5.释放资源
sqlSession.close();
}
4.此外共有四种注解,在注解里面填写相应的简单sql语句即可:
- 查询@Select
- 添加@Insert
- 修改@Update



