Mybatis是一款持久层(三层架构中的Dao,数据访问层)框架,用于简化JDBC框架,简化了JDBC书写
UserMapper就是UserDao,但是在Mybatis中为Mapper
一、创建springboot工程、构造数据库表格,实体类
实体类中构造数据库表格:
int-Integer
tinyint-short
varchar-String
二、在resourses的application中配置Mybatis,四要素
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
url中数据库名字需修改为自己所要的数据库
创建接口UserMapper
测试
JDBC(Mybatis简化前)
概念:使用java语言操作关系型数据库的一套API
缺点:资源浪费
二、数据库连接池
数据库连接池是一个容器,负责分配、管理数据库连接
允许应用程序重复利用一个现有的数据库连接,而不是重新再建一个
释放空间时间超过最大空闲时间的连接,避免因为没有释放连接而引起的数据库连接遗漏
接口:DataSource
优势:资源重用 提升系统响应速度 避免数据库连接遗漏
Druid 阿里巴巴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
三、lombok
解决实体类中方法芜杂,在publib class上面@Data
在pom中添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
四、Mybatis基本操作-增删改查crud
一、删除
// 删除
@Delete("delete from mysql_db02.emp where id = #{id}")
public void delete(Integer id);
delete方法的返回值为影响的记录数,即删除了几条数据
#配置mybaits的日志文件
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
预编译SQL:性能更高、更安全(#{id}})
SQL注入是通过输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法
password输入的是在表单中输入的密码
二、新增
//新增
@Insert("insert into mysql_db02.emp(#{username}, #{name}, #{gender}, #{image},#{ job}, #{entrydate},#{ dept_id},#{ createTime}, #{updateTime}) values ('Tom','tom',1,'1.jpg','2005-01-01',1,now(),now())")
public void insert(Emp emp);
主键返回:在数据添加成功后,获取插入数据库数据的主键。如:添加套餐数据时,还需要维护菜品关系表的数据
。只进行基础的新增操作,返回的主键id为null
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into mysql_db02.emp(#{username}, #{name}, #{gender}, #{image},#{ job}, #{entrydate},#{ dept_id},#{ createTime}, #{updateTime}) values ('Tom','tom',1,'1.jpg','2005-01-01',1,now(),now())")
public void insert(Emp emp);
三、更新(修改)
//更新数据
@Update("update mybatis01.emp set username = #{username},name = #{name},gender = #{gender},image= #{image} , job = #{job},entrydate =#{entrydate} ,dept_id = #{deptId} ,update_time =#{updateTime} where id = #{id}")
public void update(Emp emp);
测试:
@Test
void contextLoads() {
Emp emp = new Emp();
// emp.setName("tom");
// empMapper.insert(emp);
emp.setId(17);
emp.setUsername("aaa");
emp.setUpdateTime(LocalDateTime.now());
emp.setName("aaa");
emp.setGender((short)1);
emp.setJob((short)1);
emp.setEntrydate(LocalDate.of(2000,1,5));
empMapper.update(emp);
四、查询
@Select("select * from mybatis01.emp where id = #{id}")
public Emp getById(Integer id);
测试:
void contextLoads() {
Emp emp = empMapper.getById(14);
System.out.println(emp);
最后三个为null,没有封装出来
类中为驼峰命名法
解决方法一:
给字段起别名
@Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from mybatis01.emp where id = #{id}")
public Emp getById(Integer id);
@Result封装
//查询数据
@Results({
@Result(column = "dept_id",property = "deptId"),
@Result(column = "create_time",property = "createTime"),
@Result(column = "update_time",property = "UpdateTime")
})
@Select("select * from mybatis01.emp where id = #{id}")
public Emp getById(Integer id);
开启Mybatis的驼峰命名自动映射方式
application.properties中
mybatis.configuration.map-underscore-to-camel-case=true
mybatis日志配置:
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
四、条件查询
//条件查询
@Select("select * from mybatis01.emp where name like '%${name}%' and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time DESC")
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
或者用contat拼接字符串函数:
where name like concat('%',#{name},'%')
List<Emp> empList = empMapper.list("张",(short)1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
System.out.println(empList);
五、XML配置文件配置SQL语句
xml映射文件与Mapper接口名称一样,并放在相同包下
XML映射文件与namespace属性为Mapper接口全限定名一致
XML映射文件sql语句的id与Mapper接口的方法名一致,并且返回类型一致
<?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.yyy.Mapper.EmpMapper">
</mapper>
MybatisX的插件
复杂的SQL通过xml,简单的通过注解