Mybatis learning notes - basic concepts and operation

Princess SINB 2021-04-08 03:45:04
mybatis learning notes basic concepts


One 、Mybatis brief introduction

1、 What is? Mybatis?
MyBatis Is an excellent persistence layer framework :

It supports customization SQL、 Stored procedures and high-level mappings .MyBatis It dispenses with almost everything JDBC
Code and the work of setting parameters and getting result sets .MyBatis It can be done by simple XML Or annotations to configure and map primitive types 、 Interface and Java POJO(Plain Old Java Objects, Ordinary old-fashioned Java object ) For records in the database .

2、 advantage :

  • Easy to learn , flexible
  • sql Separation from code , Improved maintainability .
  • Provide mapping label , Support object and database orm Field relation mapping
  • Provide object relation mapping labels , Support object relationship building and maintenance
  • Provide xml label , Support writing dynamics sql

Two 、 Add, delete, check and change operations

1、 Write the main configuration file :

<?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>
<!-- Print log operation -->
<settings>
<setting name="cacheEnabled" value="true" />
<setting name="useGeneratedKeys" value="true" />
<setting name="defaultExecutorType" value="REUSE" />
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!-- Database configuration operations -->
<environments default="development">
<environment id="development">
<transactionManager type="jdbc"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/day_3_14?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<!-- Mapping configuration -->
<mappers>
<mapper resource="com/atguigu/mybatis/Dao/StudentDao.xml"/>
</mappers>
</configuration>

2、 Write corresponding Dao.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">
<!-- Note that the path here is the full class name , And use . separate , instead of / -->
<mapper namespace="com.atguigu.mybatis.Dao.StudentDao">
<select id="selectAllStudent" resultType="com.atguigu.mybatis.Entry.Student">
select * from student
</select>
<select id="selectById" resultType="com.atguigu.mybatis.Entry.Student">
select id,name,phone,address from student where id=#{stuId}
</select>
<insert id="insertStudent" parameterType="com.atguigu.mybatis.Entry.Student">
insert into student values(#{id},#{name},#{phone},#{address})
</insert>
<update id="updateStudent">
update student set id=#{id},name=#{name},phone=#{phone},address=#{address}
where id=#{id}
</update>
<delete id="deleteStudentById">
delete from student where id=#{id}
</delete>
</mapper>

3、 Write corresponding Dao.java


import com.atguigu.mybatis.Entry.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentDao {

// Query and return list results 
public List<Student> selectAllStudent();
// according to id The query 
public Student selectById(@Param("stuId") String id);
// Insert object operation 
public int insertStudent(Student student);
// Update object operations 
public int updateStudent(Student student);
// Delete object operation 
public int deleteStudentById(String id);
}

4、 Write the corresponding entity class

public class Student {

String id;
String name;
String phone;
String address;
public String getId() {

return id;
}
public String getName() {

return name;
}
public String getPhone() {

return phone;
}
public String getAddress() {

return address;
}
public void setId(String id) {

this.id = id;
}
public void setName(String name) {

this.name = name;
}
public void setPhone(String phone) {

this.phone = phone;
}
public void setAddress(String address) {

this.address = address;
}
@Override
public String toString() {

return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}

5、 To write mybatis Tool class

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;
public class MybatisUtil {

static SqlSessionFactory sqlSessionFactory = null;
static {

try {

// Use Mybatis First step : obtain sqlSessionFactory object 
String resource = "com/atguigu/mybatis/mybatis-mapper.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {

e.printStackTrace();
}
}
public static SqlSession getSqlSession(){

return sqlSessionFactory.openSession();
}
}

6、 Writing test classes

import com.atguigu.mybatis.Dao.StudentDao;
import com.atguigu.mybatis.Entry.Student;
import com.atguigu.mybatis.Util.MybatisUtil;
import org.apache.ibatis.annotations.Param;
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 Testdemo1 {

@Test
public void testSelect() throws IOException {

SqlSession session= MybatisUtil.getSqlSession();
List<Student> list = session.selectList("com.atguigu.mybatis.Dao.StudentDao.selectAllStudent");
System.out.println(list);
// Release resources 
session.close();
}
@Test
public void testSelectById(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.selectById";
StudentDao studentDao=sqlSession.getMapper( StudentDao.class);
Student student=studentDao.selectById("1");
System.out.println(student);
}
@Test
public void testInsert(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.insertStudent";
Student student=new Student();
student.setId("4");
student.setName("zhangfei");
student.setPhone("1435246357");
student.setAddress("shuguo");
int num=sqlSession.insert(sqlId,student);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdate(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.updateStudent";
Student student=new Student();
student.setId("4");
student.setName("guanyu");
student.setPhone("4675");
student.setAddress("shuguo");
int num=sqlSession.insert(sqlId,student);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testDelete(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.deleteStudentById";
int num=sqlSession.insert(sqlId,"4");
sqlSession.commit();
sqlSession.close();
}
}

7、 Directory structure :
 Insert picture description here

3、 ... and 、 Fuzzy query

 public List<Student> selectLike(String name);
<select id="selectLike" resultType="com.atguigu.mybatis.Entry.Student">
select id,name,address,phone from student where name like #{name}
</select>
@Test
public void testLike(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.selectLike";
List<Student> students=sqlSession.selectList(sqlId,"%z%");
System.out.println(students);
sqlSession.commit();
sqlSession.close();
}

Four 、 utilize Map Map to query

public List<Student> selectMap(Map<String,Object> map);
<select id="selectMap" resultType="com.atguigu.mybatis.Entry.Student">
select id,name,address,phone from student where name like #{name}
</select>
 @Test
public void testMap(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.selectLike";
Map<String,Object> map=new HashMap<>();
map.put("name","%z%");
List<Student> students=sqlSession.selectList(sqlId,map);
System.out.println(students);
sqlSession.commit();
sqlSession.close();
}

5、 ... and 、 dynamic sql

1、 label : If if Inside the label test Condition not satisfied , The inner statement of the label body will not be executed

public List<Student> selectIf(Student student);
<select id="selectIf" resultType="com.atguigu.mybatis.Entry.Student">
select id,name,address,phone from student where
<if test="name!=null">
name=#{name}
</if>
<if test="id!=null">
id=#{id}
</if>
</select>
 @Test
public void testIf(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.selectIf";
StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
Student student=new Student();
student.setId("1");
// student.setName("");
student.setPhone("4675");
student.setAddress("shuguo");
List<Student> students=studentDao.selectIf(student);
System.out.println(students);
sqlSession.commit();
sqlSession.close();
}

2、<where> label : This “where” The tag will know if it contains a return value in the tag , It just inserts a ‘where’. Besides , If the tag returns content with AND or OR At the beginning , Then it will eliminate .

public Student selectWhere(Student student);
 <select id="selectWhere" resultType="com.atguigu.mybatis.Entry.Student">
select id,name,address,phone from student
<where>
<if test="name!=null">
name=#{name}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
</select>
 @Test
public void testWhere(){

SqlSession sqlSession=MybatisUtil.getSqlSession();
String sqlId="com.atguigu.mybatis.Dao.StudentDao.selectIf";
StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
Student student=new Student();
student.setId("1");
// student.setName("");
student.setPhone("4675");
student.setAddress("shuguo");
Student students=studentDao.selectWhere(student);
System.out.println(students);
sqlSession.commit();
sqlSession.close();
}

here , if name It's empty , be where Statement will automatically id Before and Symbol deletion , if name And id All empty. , be where It will be deleted as well .

3、<set> label

<update id="updateUserById" parameterType="com.ys.po.User">
update user u
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</if>
</set>
where id=#{id}
</update>

4、<choose> label (when And otherwise)

<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
select * from user
<where>
<choose>
<when test="id !='' and id != null">
id=#{id}
</when>
<when test="username !='' and username != null">
and username=#{username}
</when>
<otherwise>
and sex=#{sex}
</otherwise>
</choose>
</where>
</select>

5、<foreach> label

<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
select * from user
<where>
<!--
collection: Specifies the collection properties in the input object
item: Each time the generated object is traversed
open: Concatenated string at the beginning of traversal
close: String concatenated at the end
separator: Traverse the string that needs to be spliced between objects
select * from user where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
版权声明
本文为[Princess SINB]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210408034310718w.html

  1. Spring Boot 中如何统一 API 接口响应格式?
  2. 深入分析 SpringMVC 参数解析器
  3. SpringBoot 中如何自定义参数解析器?
  4. SpringMVC 初始化流程分析
  5. 如何优雅的实现 Spring Boot 接口参数加密解密?
  6. Spring5 里边的新玩法!这种 URL 请求让我涨见识了!
  7. SpringMVC 中的参数还能这么传递?涨姿势了!
  8. 手把手教你开发 MyBatis 插件
  9. 细品 Spring Boot+Thymeleaf,还有这么多好玩的细节!
  10. Spring Boot 日志各种使用姿势,是时候捋清楚了!
  11. Deep analysis of viewresolver of nine components of spring MVC
  12. In depth analysis of handleradapter of nine components of spring MVC
  13. In depth analysis of handlermapping of nine components of spring MVC
  14. Can spring boot define interface methods to be declared private?
  15. Dispatcherservlet of spring MVC source code analysis
  16. Framework servlet for spring MVC source code analysis
  17. How to unify API response format in spring boot?
  18. In depth analysis of spring MVC parameter parser
  19. How to customize parameter parser in springboot?
  20. Analysis of spring MVC initialization process
  21. How to realize encryption and decryption of spring boot interface parameters gracefully?
  22. A new way to play in spring 5! This kind of URL request makes me see better!
  23. Can parameters in spring MVC be passed like this? It's up!
  24. Hand in hand to teach you how to develop mybatis plug-ins
  25. Fine spring boot + thymeleaf, there are so many fun details!
  26. Spring boot logs all kinds of posture, it's time to clear!
  27. Web 3.0踏浪而来,分布式存储举足轻重|时空云邀请您参加Web3.0中国峰会暨分布式存储行业大会
  28. spring-aop 进不了切面方法的解决办法
  29. Web 3.0 is coming, distributed storage is very important | spatiotemporal cloud invites you to attend Web3.0 China Summit and distributed storage industry conference
  30. The solution of spring AOP can't enter the section method
  31. Linux中如何启用root用户
  32. How to enable root in Linux
  33. 踩坑 MySQL 索引,看看你真的会用吗?
  34. Hive优化之配置参数的优化(一)
  35. Step on the MySQL index to see if you really know how to use it?
  36. Optimization of configuration parameters for hive optimization (1)
  37. Linux入门教程资料分享
  38. Introduction to Linux
  39. 外部连接mysql docker容器异常
  40. Exception of external connection MySQL docker container
  41. Zookeeper分布式锁?
  42. Zookeeper distributed lock?
  43. 嵌入式Linux_Framebuffer_03点阵显示ASCII字符串
  44. 嵌入式Linux_Framebuffer_02字符编码
  45. Embedded Linux_ Framebuffer_ 03 dot matrix display ascii string
  46. Embedded Linux_ Framebuffer_ 02 character encoding
  47. Looking forward to new product launch of Xiaomi in spring CNMO takes you to see 11 new products in advance
  48. An inventory of the commonly used garbage collectors in Java
  49. Why is it so easy to get started with HBase?
  50. Implementation of PRC framework based on netty
  51. 2021 Java back end engineer must know knowledge - (Dubbo, distributed RPC framework)
  52. 关于spring advisor和元数据 同时来管理事务的问题
  53. How to manage transactions with spring advisor and metadata at the same time
  54. 使用Playwright对Java API实现自动视觉测试 - applitools
  55. Using playwright to implement automatic visual testing for Java API - applitools
  56. Dubbo和Spring cloud、Istio对比图
  57. Comparison of Dubbo with spring cloud and istio
  58. HttpServletRequest、通过request获得请求头、请求体等、解决中文乱码等问题
  59. Mybatis学习笔记-一对一,一对多,多对多关联查询
  60. Mybatis学习笔记-基本概念与操作