首页 > 其他分享 >Web学习day04

Web学习day04

时间:2024-07-13 21:54:48浏览次数:8  
标签:Web day04 学习 EmpMapper sqlSession emp empMapper import public

mybatis


目录

mybatis

文章目录

一、查询

1.1结果映射

1.2多条件查询

1.3模糊查询

二、XML

书写规范

三、动态SQL

四、配置文件

4.1settings标签

4.2mappers标签

4.3environments标签

五、案例

5.1数据表

5.2实现类

5.3mapper实现

5.4工具类实现

5.5XML动态SQL实现

5.6XML配置实现

5.7测试实现

5.8pom.xml配置

总结


一、查询

1.1结果映射

开启驼峰映射:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。

字段起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。

@Results @Result:通过 @Results及@Result 进行手动结果映射。

1.2多条件查询

@Param 标注在方法参数的前面,用于声明参数在#{}中的名字

1.3模糊查询

${}性能低,不安全,存在SQL注入问题:

#{}推荐:

二、XML

书写规范

XML文件的名称与Mapper接口名称一致,并且放置在相同包下(同包同名)。

XML文件的namespace属性为Mapper接口全限定名一致。

XML文件中sql语句的id与Mapper 接口中的方法名一致。

XML文件中sql语句的返回类型与Mapper 接口中的方法返回类型一致。

三、动态SQL

<if>

用于判断条件是否成立,如果条件为true,则拼接SQL

<where>

where 元素只会在子元素有内容的情况下才插入where子句

而且会自动去除子句的开头的AND 或OR

<set>

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

<foreach >

用来批量处理的 比如批量删除拼接 in后面的值

<sql>

定义一个sql片段 就是提取公共的sql

<include>

引入sql片段

四、配置文件

4.1settings标签

控制一些全局配置项的开闭

4.2mappers标签

加载Mapper接口位置

4.3environments标签

Druid(德鲁伊):  阿里巴巴提供的数据库连接池技术,国内使用率很高,提供了完善的监控机制

HikariCP:  日本人开发的连接池技术,号称性能之王,速度最快,SpringBoot2.0默认使用此连接池

五、案例

5.1数据表

5.2实现类

代码如下(示例):

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Short gender;
    private String image;
    private Short job;

    //注意:这四个属性跟数据表中的字段不一致
    private LocalDate ed;

    private Integer deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

5.3mapper实现

代码如下:

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

public interface EmpMapper {

    @Select("select * from emp")
    public List<Emp> findAll();

    @Select("select * from emp")
    public List<Emp> findAll1();

    @Select("select id,username,password,name,gender,image,job,entrydate ed,dept_id,create_time,update_time from emp")
    public List<Emp> findAll2();

    @Select("select * from emp")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findAll3();

    @Select("select * from emp where name =#{name} and gender = #{gender} and entrydate between #{begin} and #{end} ")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findByCondition(@Param("name") String name,@Param("gender") Integer gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);

    @Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} ")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findByCondition2(@Param("name") String name,@Param("gender") Integer gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);

    public Emp findById(Integer id);

    List<Emp> findByCondition3(@Param("name") String name,@Param("gender") Short gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);
    
    void update(Emp emp);

    void deleteByIds(@Param("ids") List<Integer> ids);
}

5.4工具类实现

代码如下:

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.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    //保证SqlSessionFactory仅仅创建一次
    static {
        try {
            //读取配置文件
            InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取sqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    //提交事务 关闭sqlSession
    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
        }
    }
}

5.5XML动态SQL实现

代码如下:

<?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.itheima.mapper.EmpMapper">

    <sql id="mySql">
        select * from emp
    </sql>

    <resultMap id="MyMap" type="com.itheima.domain.Emp">
        <result column="entrydate" property="ed"/>
    </resultMap>
    <select id="findById" resultMap="MyMap">
        <include refid="mySql"/>
        where id = #{id}
    </select>


    <select id="findByCondition3" resultType="com.itheima.domain.Emp">
        <include refid="mySql"/>
        <where>
            <if test="name != null and name !=''">
                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>
    </select>

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

    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>


</mapper>

5.6XML配置实现

代码如下:

<?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"/>
        <!--在控制台输出发送的sql日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>


    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>

            <!--目前只关注这部分内容,它的作用就是声明要连接的数据信息-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--声明含有sql的接口所在包-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

5.7测试实现

代码如下:

package com.itheima.test;

import com.itheima.domain.Emp;
import com.itheima.mapper.EmpMapper;
import com.itheima.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

public class EmpMapperTest {

    // 测试查询所有
    @Test
    public void testFindAll(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射开启驼峰命名规则
    @Test
    public void testFindAll1(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll1();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射起别名
    @Test
    public void testFindAll2(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll2();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射手动结果映射@Results @Result
    @Test
    public void testFindAll3(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll3();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试条件查询
    @Test
    public void testFindCondition(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findByCondition("张三丰",1, LocalDate.of(2000,1,1),LocalDate.of(2020,1,1));
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试模糊查询
    @Test
    public void testFindCondition2(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findByCondition2("张",1, LocalDate.of(2000,1,1),LocalDate.of(2020,1,1));
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试根据id查询
    @Test
    public void testFindById(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp1 = empMapper.findById(4);
        System.out.println(emp1);
        MybatisUtil.close(sqlSession);
    }

    //条件查询
    @Test
    public void testFindByCondition() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        //List<Emp> empList = empMapper.findByCondition3("张", (short) 1, LocalDate.of(2002, 01, 01), LocalDate.of(2023, 12, 31));
        //List<Emp> empList = empMapper.findByCondition3("张", (short) 1, null, null);
        List<Emp> empList = empMapper.findByCondition3("", (short) 1, null, null);
        empList.forEach(e -> System.out.println(e));//lambda方式打印

        MybatisUtil.close(sqlSession);
    }

    //更新
    @Test
    public void testUpdate() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        Emp emp = new Emp();
        emp.setId(2);
        emp.setUsername("haha2");
        emp.setName("sdnajn");
        emp.setGender( (short) 1);
        emp.setImage("haha.jpg");
        emp.setJob((short) 2);
        emp.setDeptId(1);
        emp.setCreateTime(LocalDateTime.of(2023, 1, 1, 1, 1,1));
        emp.setUpdateTime(LocalDateTime.now());

        empMapper.update(emp);

        MybatisUtil.close(sqlSession);
    }

    //批量删除
    @Test
    public void deleteByIds() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        empMapper.deleteByIds(Arrays.asList(13, 14, 15));

        MybatisUtil.close(sqlSession);
    }

}

5.8pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day04-01-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
    </dependencies>

</project>

总结

以上就是今天学习的内容。

标签:Web,day04,学习,EmpMapper,sqlSession,emp,empMapper,import,public
From: https://blog.csdn.net/filthy555/article/details/140406602

相关文章

  • 关于Hadoop学习
    Hadoop是一个开源的分布式计算框架,被广泛应用于大数据处理和分析中。作为一个学习Hadoop的初学者,我不仅对其强大的功能和灵活性感到震撼,还深刻体会到了学习这一技术所需的耐心和毅力。在这篇文章中,我将分享我学习Hadoop的体会和心得。学习Hadoop需要具备一定的计算机基础知识和编......
  • 每周JAVA学习汇总
    本周我自学了Java的输入与输出包括了:使用Scanner类进行输入导入Scanner类:importjava.util.Scanner;创建Scanner对象:Scannerscanner=newScanner(System.in);读取不同类型的数据:读取字符串:StringinputString=scanner.nextLine();读取整数:intinputInt=scanner.ne......
  • Java学习第二周
    标识符是用来给变量,类,方法以及包进行命名的。标识符的命名规则1.必须以字母、下划线“”、美元符“$”开头。2.其他部分可以是字母、下划线“”、美元符“$”和数字的人员组合·。3.大小写敏感,且长度无限制。4.不可以是Java的关键字。标识符使用规范表示类名的标识符:每个单......
  • 2024.07.06 hadoop学习
    这是暑假自学的第一周,在这里做一个周总结。自从考完试之后,数据库小学期也开始了,所以我在下午进行自学,这一周自学的内容是javaweb。这一周每天下午都会抽出一小时的时间学习,学习的主要内容是javaweb中的maven,连接数据库,进行CRUD开发。在学习maven的过程中,主要使用半成品框架......
  • Hadoop学习总结
    在我作为初学者探索Hadoop的过程中,我深感兴奋和好奇。Hadoop作为一种开源的分布式存储和计算平台,能够处理大规模数据,这一点让我产生了深刻的震撼和兴趣。刚开始接触时,我面临理解Hadoop核心概念的挑战,特别是涉及到HDFS(Hadoop分布式文件系统)和MapReduce的概念。然而,通过阅读官方文档......
  • 第一周学习总结
    开篇概述随着计算机网络基础设施的完善,社交网络和电商的发展以及物连网的推进,产生了越来越多的大数据,使得人工智能最近几年也有了长足的发展(可供机器学习的样本数据量足够大了),大数据的存储和处理也越来越重要,国家对此也比较重视(可上网搜索关键字“大数据白皮书”关键字,以了解详细......
  • 第二周学习总结
    分布式文件系统主要用来解决如下几个问题:读写大文件加速运算对于某些体积巨大的文件,比如其大小超过了计算机文件系统所能存放的最大限制或者是其大小甚至超过了计算机整个硬盘的容量的文件,这时需要将文件分割为若干较小的块,然后将这些块按照一定的规则分放在集群中若干台节点......
  • Python学习笔记36:进阶篇(二十五)pygame的使用之事件监听控制切歌和暂停,继续播放
    前言基础模块的知识通过这么长时间的学习已经有所了解,更加深入的话需要通过完成各种项目,在这个过程中逐渐学习,成长。我们的下一步目标是完成pythoncrashcourse中的外星人入侵项目,这是一个2D游戏项目。在这之前,我们先简单学习一下pygame模块。私信我发送消息python资料,......
  • 【WebGIS期末作业】
    项目背景表1湖南传统村落不同批次占全国总数分布表随着现代化和城镇化进程的加快,根据2017年发布中国传统村落蓝皮书显示,4153个传统村落面临消失危险,大部分传统村落现主要面临以下4个问题:传统村落数量锐减、毁坏严重、非物质文化遗产面临断层以及建设性破坏与环境污染,因此......
  • hadoop学习
    作为一个开源框架,Hadoop让大数据处理变得更加简便而高效。学习Hadoop对于处理大规模数据集是一个非常有价值的技能。Hadoop不仅仅是一个技术框架,更是一种处理大数据的思维方式。它通过将数据划分为多个小块,并在集群中的多个节点上并行处理,从而实现了对海量数据的快速处理。Hadoop......