Mybatis&Mybatis-Plus

2023-12-28 20:39:33

一、idea开发mybatis

1.导入坐标

? ? ? ? 在pom.xml文件中导入所需要的坐标

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>

2.构造实体类

public class Student {
    private int stuId;
    private String stuName;
    private String stuHobby;
    private String stuAge;

    @Override
    public String toString() {
        return "Student{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuHobby='" + stuHobby + '\'' +
                '}';
    }

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuHobby() {
        return stuHobby;
    }

    public void setStuHobby(String stuHobby) {
        this.stuHobby = stuHobby;
    }

    public Student(){

    }

    public Student(String stuName, String stuHobby) {
        this.stuName = stuName;
        this.stuHobby = stuHobby;
    }

    public Student(int stuId, String stuName, String stuHobby) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuHobby = stuHobby;
    }
}

3.配置文件

StudentMapper文件:

public interface StudentMapper {

    @Insert("insert into student(stu_name,stu_hobby) values(#{stuName},#{stuHobby})")
    public void saveStu(Student student);

    @Select("select * from student")
    public List<Student> findAll();
}

Application.xml文件:

<?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>

    <!--全局设置-->
    <settings>
        <!--自动驼峰映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--开发模式-->
    <environments default="env">
        <environment id="env">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/230809db?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--注册映射器-->
    <mappers>
        <package name="com.apesource.dao"/>
    </mappers>
</configuration>

4.编写映射器

public interface StudentMapper {

    @Insert("insert into student(stu_name,stu_hobby) values(#{stuName},#{stuHobby})")
    public void saveStu(Student student);

    @Select("select * from student")
    public List<Student> findAll();
}

5.测试

public class Test01 {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/230809db?serverTimezone=GMT", "root", "123456");
            System.out.println(root);
        } catch (ClassNotFoundException exception) {
            exception.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}

mybatis自动驼峰映射

JavaBean

DB
stuId

stu_id

stuNamestu_name
stuHobbystu_hobby

开启自动驼峰映射步骤:配置文件中配置mapUnderscoreToCamelCase

<settings>
        <!--自动驼峰映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

junit

含义:junit专业测试方法的工具

注意:在test目录下的java目录下创建包的时候,包的名称必须与main下的java目录里面的父包名称一致

步骤:

1.坐标

<dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.13.2</version>
     <scope>test</scope>
</dependency>

2.注解:修饰在方法上

????????@Test=========》main

????????@Before=======》在@Test直接执行之前运行

????????@After========》在@Test直接执行之后运行

public class Test01 {
    InputStream inputStream = null;
    SqlSession sqlSession = null;
    StudentMapper mapper = null;

    @Before
    public void beforeMethod(){
        try {
            inputStream = Resources.getResourceAsStream("Application.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = sqlSessionFactoryBuilder.build(inputStream);
            sqlSession = factory.openSession(true);
            mapper = sqlSession.getMapper(StudentMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void afterMethod(){
        try {
            sqlSession.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void findAll(){
        List<Student> all = mapper.findAll();
        for (int i = 0; i < all.size(); i++) {
            Student student =  all.get(i);
            System.out.println(student);
        }
    }


    @Test
    public void save(){
            Student student1 = new Student("张三","敲代码~");
            Student student2 = new Student("李四","唱跳rap");
            Student student3 = new Student("王五","篮球");
            mapper.saveStu(student1);
            mapper.saveStu(student2);
            mapper.saveStu(student3);
    }

}

lombok

步骤:

1.idea开发工具安装插件(有且只做一次)

2.坐标

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

3.注解

  1. @Data:该注解会自动生成 getter、setter、equals、hashCode 和 toString 方法,同时还会生成一个无参构造函数和一个拷贝构造函数。
  2. @Getter:该注解用于生成指定字段的 getter 方法。
  3. @Setter:该注解用于生成指定字段的 setter 方法。
  4. @NoArgsConstructor:该注解用于生成一个无参构造函数。
  5. @AllArgsConstructor:该注解用于生成一个包含所有字段的构造函数。
  6. @ToString:该注解用于生成一个 toString 方法,该方法将返回类名和字段值的字符串表示形式。
  7. @EqualsAndHashCode:该注解用于生成 equals 和 hashCode 方法,用于比较对象是否相等。
  8. @Slf4j:该注解用于生成一个 logger 对象,用于记录日志。
  9. @Log4j:该注解用于生成一个 Log4j logger 对象,用于记录日志。

mybatis-plus

步骤:

1.坐标

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.1.1</version>
</dependency>

? ? ? ? 注意:mp坐标添加后,mybatis坐标移除

2.编写注解配置实体类与关系表映射关系(truncate清空表以及主键)

? ? ? ? @TableName(value = "关联表名称")????????修饰在类

? ? ? ? @TableField(value = "关联字段名称")????????修饰在属性

? ? ? ? ? ? ? ? ? ? ? ? ? ? ?exist = "忽略字段"

? ? ? ? @TableId(type="指定主键生成策略,默认雪花算法")????????修饰在属性

  • ? ? ? ? ? ? ? ? ? ? AUTO(0),
  • ? ? ? ? ? ? ? ? ? ? NONE(1),
  • ? ? ? ? ? ? ? ? ? ? INPUT(2),
  • ? ? ? ? ? ? ? ? ? ? ASSIGN_ID(3),
  • ? ? ? ? ? ? ? ? ? ? ASSIGN_UUID(4);
  • @TableName(value = "student")
    public class Student {
        @TableId(value = "stuid",type = IdType.AUTO)
        private int stuId;
        @TableField(value = "stuname")
        private String stuName;
        @TableField(value = "stuhobby")
        private String stuHobby;
        @TableField(value = "stuage")
        private String stuAge;
    
        public Student(String stuName, String stuHobby) {
            this.stuName = stuName;
            this.stuHobby = stuHobby;
        }
    }

? ? 3.使用

? ? ? ? BaseMapper????????公共的数据访问层

? ? ? ? IService/ServiceImp????????公共的业务层

public interface StudentMapper extends BaseMapper<Student> {
    @Insert("insert into student(stuname,stuhobby) value(#{stuName},#{stuHobby})")
    public void saveStu(Student student);

    @Select("select * from student")
    public List<Student> findAll();
}

? ? 4.测试代码使用MyBatisSqlSessionFactoryBuilder

public class Test03 {
    InputStream inputStream = null;
    SqlSession sqlSession = null;
    StudentMapper mapper = null;

    @Before
    public void beforeMethod(){
        try {
            //1.加载资源文件
            inputStream =  Resources.getResourceAsStream("mybatis.xml");
            //2.创建构造器
            MybatisSqlSessionFactoryBuilder builder = new MybatisSqlSessionFactoryBuilder();
            //3.创建工厂
            SqlSessionFactory factory = builder.build(inputStream);
            //4.获取会话
            sqlSession =  factory.openSession(true);
            //5.加载映射器
            mapper =  sqlSession.getMapper(StudentMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void afterMethod(){
        try {
            sqlSession.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void findAll(){
        List<Student> all = mapper.findAll();
        for(int i = 0; i< all.size();i++){
            Student student = all.get(i);
            System.out.println(student);
        }
    }

    @Test
    public void show1(){
       //1.条件查询
        LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<Student>();
        lambdaQueryWrapper.eq(Student::getStuName,"123");
        //2.查询
        List<Student> list = mapper.selectList(lambdaQueryWrapper);
        for (int i = 0; i < list.size(); i++) {
            Student student =  list.get(i);
            System.out.println(student);
        }
    }

    //模拟动态查询1
    @Test
    public void test02(){
        Integer num1 = null;
        Integer num2 = 30;
        //1.查询条件
        LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<Student>();
        //2.判断
        if (null != num2){
            lambdaQueryWrapper.lt(Student::getStuAge,num2);
        }
        if (null != num2){
            lambdaQueryWrapper.gt(Student::getStuAge,num1);
        }
        //3.查询
        List<Student> list =  mapper.selectList(lambdaQueryWrapper);
        for (int i = 0; i < list.size(); i++) {
            Student student =  list.get(i);
            System.out.println(student);
        }
    }

    //模拟动态查询2
    @Test
    public void show3(){
        //1.前端发送来的数据
        Integer num1 = null;
        Integer num2 = 30;

        //1.查询条件
        LambdaQueryWrapper<Student> lambdaQueryWrapper =  new LambdaQueryWrapper<Student>();
        //2.判断
        lambdaQueryWrapper.lt(null != num2, Student::getStuAge,num2);
        lambdaQueryWrapper.gt(null != num1, Student::getStuAge,num1);
        //3.查询
        List<Student> list =  mapper.selectList(lambdaQueryWrapper);
        for (int i = 0; i < list.size(); i++) {
            Student student =  list.get(i);
            System.out.println(student);
        }
    }

    //投影查询-字段查询
    @Test
    public void show4() {
        //1.条件
        LambdaQueryWrapper<Student> lambdaQueryWrapper  = new LambdaQueryWrapper<Student>();
        lambdaQueryWrapper.select(Student::getStuName, Student::getStuHobby);

        //2.查询
        List<Student> list =  mapper.selectList(null);
        //4.遍历
        for (int i = 0; i < list.size(); i++) {
            Student student =  list.get(i);
            System.out.println(student);
        }
    }

    //投影查询-聚合查询
    @Test
    public void show5() {
        //1.查询条件
        QueryWrapper queryWrapper = new QueryWrapper<Student>();
        //2.判断
        queryWrapper.select("count(*) as num1,sum(stu_age) as num2,max(stu_age) as num3");
        //3.查询
        List<Map<String,Object>> list =  mapper.selectMaps(queryWrapper);
        //4.遍历
        System.out.println(list);

    }

    //分组查询
    @Test
    public void show6() {
        //1.查询条件
        QueryWrapper queryWrapper = new QueryWrapper<Student>();
        //2.判断
        queryWrapper.select("count(*) as num1,stu_hobby");
        queryWrapper.groupBy("stu_hobby");
        //3.查询
        List<Map<String,Object>> list =  mapper.selectMaps(queryWrapper);
        //4.遍历
        System.out.println(list);
    }


    /**
     * 物理删除:业务数据从数据库中丢弃,执行的是delete操作
     * 逻辑删除:为数据设置是否可用状态字段,删除时设置状态字段为不可用状态,
     *         数据保留在数据库中,执行的是update操作
     *         实现步骤:
     *          步骤1:修改数据库表添加`deleted`列,比如`0`代表正常,`1`代表删除,可以在添加列的同时设置其默认值为`0`正常。
     *          步骤2:实体类添加属性以及注解
     *          @TableLogic(value="0",delval="1")
     *          private Integer deleted;
     *              value为正常数据的值,delval为删除数据的值
     * */

    //逻辑删除
    @Test
    public void show7() {
        mapper.deleteById(6);
    }

}

?

文章来源:https://blog.csdn.net/m0_73514610/article/details/135222069
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。