做网站资讯,在线做字网站,宁波妇科,姑苏区做网站四、Mybatis
概念#xff1a; Mybatis是一款持久层#xff08;Dao层#xff09;框架#xff0c;用于简化JDBC#xff08;Sun操作数据库的规范#xff0c;较繁琐#xff09;的开发
历史#xff1a; Apache的一个开源项目iBatis#xff0c;2010年由apache迁移到了goog…四、Mybatis
概念 Mybatis是一款持久层Dao层框架用于简化JDBCSun操作数据库的规范较繁琐的开发
历史 Apache的一个开源项目iBatis2010年由apache迁移到了google code并改名MyBatis。2013年11月迁移到Github
1. 入门程序
1创建Spring module创建的时候勾选MyBatis Framework和MySql service对应数据库的类型
2准备数据以及数据库环境
3定义一个实体类实体类的变量要与表中的数据类型以及名称对应实体类变脸阿哥使用包装类命名使用驼峰命名
4创建Mybatis的环境在模块的application.properties中声明
#驱动类名称
spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.urljdbc:mysql://124.221.237.48地址:3306/test数据库名
#连接数据库的用户名
spring.datasource.usernamexy
#连接数据库的密码
spring.datasource.password123456
5定义mapper就是使用Sql语句的类要使用Mapper进行注解这样运行时会自动生成该接口的实现类对象代理对象并将该对象交给IOC容器管理。
在类中定义抽象方法如果是查询就使用Select()注解括号中指定sql查询语句
注要想有sql语法提示
选中Sql语句右键Show Context Actions——inject language——MySql要想提示表名要将数据库连接到IDEA——使用IDEA连接数据库 6在测试启动类中编写测试方法因为要使用mapper接口中的方法所以使用Autowired从IOC中获取bean对象
2. 数据库池连接
使用配置文件进行配置之后SpringBoot底层就会自动使用数据库连接池技术管理和分配连接
概念
数据库连接池是个容器负责分配、管理数据库连接它允许应用程序重复使用一个现有的数据库连接而不是再重建一个释放空闲时间超过最大空闲事件的连接来避免因为没有释放连接而一起的数据库连接遗漏
优势
资源重用提升系统响应速度避免数据库连接遗漏
产品
Druid
引入依赖版本要对应调整
# Spring2
dependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-starter/artifactIdversion1.2.8/version
/dependency# Spring3
dependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-3-starter/artifactIdversion1.2.20/version
/dependency配置数据库连接池类型可以不
Hikarispringboot默认
3. lombok工具包
原有问题 数据库中的数据要对应一个实体类并为其生成构造器getter/settertoString等方法
lombok 一个实用的java类库能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法并可以自动化生成日志变量简化java开发提高效率 准备工作 添加依赖
dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId
/dependency注 Lombok会在编译时自动生成对应的java代码。我们使用lombok时还需要安装一个lombok的插件idea自带
4. Mybatis基础操作
1删除
EmpMapper.java
Mapper
public interface EmpMapper {// 根据ID删除数据Delete(delete from emp where id #{id})public void delete(Integer id);
}
// #{}是占位符生成的就是预编译的SQL语句测试方法
SpringBootTest
class SpringbootMybatisCrudApplicationTests {Autowiredprivate EmpMapper empMapper;Testpublic void testDelete() {empMapper.delete(17);}
}想要查看执行的日志信息可以配置预编译SQL
# 配置mybatis日志指定输出到控制台
mybatis.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl参数占位符 2新增
接口方法
// 插入数据
Insert(insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values(#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime}))
public void insert(Emp emp); // 参数太多使用实体类进行封装测试方法
Test
public void testInsert() {Emp emp new Emp();emp.setUsername(Tom);emp.setName(汤姆);emp.setImage(1.jpg);emp.setGender((short)1);emp.setJob((short)1);emp.setEntrydate(LocalDate.of(2000, 1, 1));emp.setCreateTime(LocalDateTime.now());emp.setUpdateTime(LocalDateTime.now());emp.setDeptId(1);empMapper.insert(emp);}主键返回
插入数据成功后想要获取这个插入数据的主键
Options(useGeneratedKeys true, keyProperty id)
Insert(insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values(#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime}))
public void insert(Emp emp);3更新
根据主键id查询回显
然后修改对应数据
Update(更新的SQL语句)
4查询
// 根据ID查询数据
Select(select * from emp where id #{id})
public Emp getById(Integer id);Test
public void testGetById() {Emp emp empMapper.getById(1);System.out.println(emp);
}数据封装
实体类属性名和数据库表查询返回的字段名一致mybatis会自动封装如果实体类属性名和数据库表查询返回的字段名不一致不能自动封装数据库属性命名是下划线分隔实体类变量命名是驼峰
解决数据封装问题
方案一给数据库字段起别名
方案二通过ResultsResult注解手动映射封装
// 通过Results和Result注解进行封装
Results({Result(column dept_id, property deptId),Result(column create_time, property createTime),Result(column update_time, property updateTime)
})
Select(select * from emp where id #{id})
public Emp getById(Integer id);方案三开启Mybatis的驼峰命名自动映射开关前提数据库字段名字和Java中的属性名命名都是严格按照规范的
# 开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-casetrue条件查询
// 条件查询
// Select(select * from emp where name like%${name}% and gender#{gender} and entrydate between #{begin} and #{end} order by update_time desc)
// public ListEmp list(String name, Short gender, LocalDate begin, LocalDate end);
// 为了防止SQL注入
Select(select * from emp where name like concat(%, #{name}, %) and gender#{gender} and entrydate between #{begin} and #{end} order by update_time desc)
public ListEmp list(String name, Short gender, LocalDate begin, LocalDate end);Test
public void testSelect() {
ListEmp empList empMapper.list(张, (short)1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
System.out.println(empList);
}5. XML映射文件配置SQL语句 条件查询的XML映射文件 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.itheima.mapper.EmpMapper!--第一个参数是方法名第二个参数是查询返回的单条语句的全类名--select idlist resultTypecom.itheima.pojo.Empselect * from emp where name like concat(%, #{name}, %) and gender#{gender} and entrydate between #{begin} and #{end} order by update_time desc/select
/mapperMybatisX是一款基于IDEA的快速开发Mybatis的插件为效率而生
使用注解来映射简单的语句会使代码更加简洁但是稍微复杂一点就混乱不堪。——如果做一些复杂的操作最好使用XML来映射语句
6. 动态SQL
概念 随着用户的输入或者外部条件的变化而变化的SQL语句
6.1 if
mapper namespacecom.itheima.mapper.EmpMapper!--第一个参数是方法名第二个参数是查询返回的单条语句的全类名--select idlist resultTypecom.itheima.pojo.Empselect *from empwhereif testname ! nullname like concat(%, #{name}, %)/ifif testgender ! nulland gender #{gender}/ifif testbegin ! null and end ! nulland entrydate between #{begin} and #{end}/iforder by update_time desc/select/mapperTest
public void testSelect() {// ListEmp empList empMapper.list(张, (short)1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));ListEmp empList empMapper.list(张, null, null, null);System.out.println(empList);
}问题 如果第一个为空wher就会紧跟着and不合规的SQL
解决 使用where/where 代替where
动态生成where关键字自动去除条件前的and和or
mapper namespacecom.itheima.mapper.EmpMapper!--第一个参数是方法名第二个参数是查询返回的单条语句的全类名--select idlist resultTypecom.itheima.pojo.Empselect *from empwhereif testname ! nullname like concat(%, #{name}, %)/ifif testgender ! nulland gender #{gender}/ifif testbegin ! null and end ! nulland entrydate between #{begin} and #{end}/if/whereorder by update_time desc/select/mapperset/set
去掉字段之后多余的逗号
6.2 foreach
!--批量删除--
!--
collection遍历的集合
item遍历的元素
separator分隔符
open遍历开始前拼接的SQL片段
close遍历结束后拼接的SQL片段
--
delete iddeleteByIdsdelete from emp where id inforeach collectionids itemid separator, open( close)#{id}/foreach
/delete// 批量删除
public void deleteByIds(ListInteger ids);Test
public void testDeletByIds() {ListInteger ids Arrays.asList(13, 14, 15);empMapper.deleteByIds(ids);
}6.3 sqlinclude
重复SQL片段——》代码复用性差