您的位置:首页 > 娱乐 > 八卦 > Mybatis

Mybatis

2024/10/6 0:34:29 来源:https://blog.csdn.net/m0_46702681/article/details/139636239  浏览:    关键词:Mybatis

目录

准备环境 

数据库连接池

lombok

 删除数据

mybatis的日志输出

新增操作 

新增(主键返回)

更新 

查询(根据ID查询) 

数据封装

可以给字段起别名,让别名与实体类属性一致 

通过@Results,@Result注解手动映射封装 

开启mybatis的驼峰命名自动映射开关 

查询(条件查询) 

XML映射文件

MyBatis动态sql 

 



准备环境 

配置Mybatis(数据库连接信息)

 在application.properties配置下面的信息

#驱动类名称

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=root

一定要注意数据库的名字和密码是否相同 

查询所有用户数据

mapper接口

package com.example.springbootmybatis.mapper;import com.example.springbootmybatis.Pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper//在运行时,会自动生成该接口的实现类对象(代理对象),并且将该对象交给I0C容器管理
public interface UserMapper {//查询全部用户信息@Select("select * from user")public List<User> list();
}

数据库连接池

是一个容器,负责分配、管理数据库连接(Connection)优势:资源复用、提升系统响应速度
接口:DataSource
产品:C3P0、DBCP、Druid、Hikari 

介绍一个数据库连接池

Druid(德鲁伊)

Druid连接池是阿里巴巴开源的数据库连接池项目,功能强大,性能优秀,是Java语言最好的数据库连接池之一

这是坐标,放入pom里👇

<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency>

lombok

Lombok是一个实用的Java类库,能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、tostring等方法,并可以自动化生成日志变量,简化java开发、提高效率。 

 @Getter/@Setter                为所有的属性提供get/set方法
@ToString                会给类自动生成易阅读的 toString 方法
@EqualsAndHashCode        根据类所拥有的非静态字段自动重写 equals 方法和 hashcode 方法
@Data提供了更综合的生成代码功能(@Getter+@Setter+@ToString+@EqualsAndHashCode)为实体类
@NoArgsConstructor        生成无参的构造器方法
@AllArgsConstructor        为实体类生成除了static修饰的字段之外带有各参数的构造器方法。

要想使用lombok还得加入他的依赖

<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>

 删除数据

mapper接口: 

package com.example.springbootmybatis.mapper;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface EmpMapper {//根据ID删除数据@Delete("delete from emp where id=#{id}")public void delete(Integer id);
}

测试:

package com.example.springbootmybatis;import com.example.springbootmybatis.Pojo.User;
import com.example.springbootmybatis.mapper.EmpMapper;
import com.example.springbootmybatis.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTest
class SpringbootMybatisApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic void testListUser(){empMapper.delete(17);}}

如果mapper接口方法形参只有一个普通类型的参数,#{..}里面的属性名可以随便写,如:#{id}、#{value},但是尽量与形参保持一致

mybatis的日志输出

在application.properties里配置

#配置mybatis的日志,指定输出到控制台

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 

这个问号是一个参数占位符,最后在运行的时候会用下面的参数去替代 

预编译SQL
                优势 :性能更高,更安全(防止SQL注入) 

新增操作 

mapper接口: 

package com.example.springbootmybatis.mapper;import com.example.springbootmybatis.Pojo.Emp;import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface EmpMapper {//新增员工操作@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);
}

 测试

package com.example.springbootmybatis;import com.example.springbootmybatis.Pojo.Emp;
import com.example.springbootmybatis.Pojo.User;
import com.example.springbootmybatis.mapper.EmpMapper;
import com.example.springbootmybatis.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;@SpringBootTest
class SpringbootMybatisApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic void testListUser(){/*empMapper.delete(17);*/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);}}

新增(主键返回)

描述:在数据添加成功后,需要获取插入数据库数据的主键。

在mapper接口中

@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);

更新 

mapper接口:

  //更新员工@Update("update 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);
}

查询(根据ID查询) 

mapper接口:

//根据id查询员工@Select("select * from emp where id=#{id}")public Emp getById(int i);

 测试

 @Testpublic void getByIdTest(){Emp byId = empMapper.getById(20);System.out.println(byId);}

数据封装

实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装

可以发现这三个并没有值 ,实体类属性名 和 数据库表查询返回的字段名不一致

可以给字段起别名,让别名与实体类属性一致 

//根据id查询员工@Select("select id, username, password, name, gender, image, job, entrydate, " +"dept_id deptId, create_time createTime, update_time  updateTime from emp where id=#{id}")public Emp getById(int i);

通过@Results,@Result注解手动映射封装 

column表示字段名,property表示属性名

 @Results({@Result(column = "dept_id",property = "deptId"),@Result(column = "create_time",property = "createTime"),@Result(column = "update_time",property = "updateTime"),})@Select("select id, username, password, name, gender, image, job, entrydate, " +"dept_id deptId, create_time createTime, update_time  updateTime from emp where id=#{id}")public Emp getById(int i);

开启mybatis的驼峰命名自动映射开关 

在application.properties里配置

#开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true

查询(条件查询) 

其中员工姓名,支持模糊匹配;性别 进行精确查询 ;入职时间 进行范围查询。并对查询的结果,根据最后修改时间进行倒序排序 

#{}不能出现在引号中,所以用${}

//条件查询@Select("select * from emp where name like '%${name}%' and gender =#{gender} and entrydate between #{begin} and #{end} order by update_time desc ")public List<Emp> Emplist(String name,Short gender, LocalDate begin , LocalDate end);

 @Testpublic void TestEmpList(){List<Emp> empList = empMapper.Emplist("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));System.out.println(empList);}

 可以用concat字符串拼接函数处理 #{}不能出现在引号中,所以用${}

   //条件查询@Select("select * from emp where name like concat('%',#{name},'%') and gender =#{gender} and entrydate between #{begin} and #{end} order by update_time desc ")public List<Emp> Emplist(String name,Short gender, LocalDate begin , LocalDate end);
}

XML映射文件

规范

  1. XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)
  2. XML映射文件的namespace属性为Mapper接口全限定名一致
  3. XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。 

 

MyBatis动态sql 

 <if>

<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL 

<where>:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。

<select id="Emplist" resultType="com.example.springbootmybatis.Pojo.Emp">select *from emp<where><if test="name!=null">name like concat('%', #{name}, '%')</if><if test="gender!=null">and gender = #{gender}</if><if test="begin!=null and end!=null">and entrydate between #{begin} and #{end}</if></where>order by update_time desc</select>

再来看看在更新员工信息时会不会出现报错 

mapper.xml映射文件中:

 <update id="update2">update empset <if test="username!=null">username=#{username},</if><if test="name!=null">name=#{name},</if><if test="gender!=null">gender=#{gender},</if><if test="image!=null">image=#{image},</if><if test="job!=null">job = #{job},</if><if test="entrydate!=null">entrydate=#{entrydate},</if><if test="deptId!=null">dept_id=#{deptId},</if><if test="updateTime!=null">update_time=#{updateTime}</if>where id = #{id}</update>

 测试

  @Testpublic void testUpdate2(){Emp emp=new Emp();emp.setId(18);emp.setUsername ("Tom111" );empMapper.update2(emp);}

 

 这个地方有个逗号

我们可以加个set标签

<update id="update2">update emp<set><if test="username!=null">username=#{username},</if><if test="name!=null">name=#{name},</if><if test="gender!=null">gender=#{gender},</if><if test="image!=null">image=#{image},</if><if test="job!=null">job = #{job},</if><if test="entrydate!=null">entrydate=#{entrydate},</if><if test="deptId!=null">dept_id=#{deptId},</if><if test="updateTime!=null">update_time=#{updateTime}</if></set>where id = #{id}</update>

<set>:动态地在行首插入 SET关键字,并会删掉额外的逗号。(用在update语句中) 

<foreach>

一般用在批量删除 

collection:集合名称

item:集合遍历出来的元素/项

separator:每一次遍历使用的分隔符

open:遍历开始前拼接的片段

close:遍历结束后拼接的片段

 <!--批量删除(18,19,20)--><delete id="deleteByIds">delete from emp where id in<foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach></delete>

 

 

<sql> <include>

<sql>:定义可重用的 SQL 片段。
<include>:通过属性refid,指定包含的sql片段。 

 以后项目如果要修改字段名的话,会很麻烦

这个时候就可以用<sql> <include>

 <sql id="commonSelect">select id,username,password,name,gender,image,job,entrydate,dept_id,create_time,update_timefrom emp</sql><select id="Emplist" resultType="com.example.springbootmybatis.Pojo.Emp"><include refid="commonSelect"></include>


Mybatis就先说到这里啦

努力遇见更好的自己!!!

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com