Mybatis

发布时间 2023-03-25 15:08:56作者: Paker_01

Mybatis

1、持久层:负责数据保存到数据库的那一层代码

JavaEE分为三层架构:表现层、业务层、持久层

2、JDBC五步走

  1. 加载驱动(这是第三方数据库给连接数据库的标准驱动)
  2. 建立连接(连接好数据库)
  3. 创建statement对象(创建执行者)
  4. 执行SQL(执行命令)语句,返回sql语句的执行结果
  5. 关数据库(关闭数据库连接,并且释放资源)

3、Mybatis的使用步骤

  1. 导入pom坐标

    		 <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.29</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.30</version>
            </dependency>
    
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.2.3</version>
            </dependency>
    
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.2.3</version>
            </dependency>
    
  2. 编写Mybatis配置文件--------mybatis-config

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <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///jdbc2"/>
                    <property name="username" value="root"/>
                    <property name="password" value="200126"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!--加载SQL映射文件-->
            <mapper resource="Test"/>
        </mappers>
    </configuration>
    
  3. 编写SQL映射文件Mapper

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace为命名空间-->
    <mapper namespace="Test">
        <select id="selectAll" resultType="com.itpak.pojo.User">
            select * from user
        </select>
    </mapper>
    
  4. 编码操作

    1. 定义pojo类
    2. 加载配置文件,获取SqlSessionFactory对象
    3. 获取SqlSession对象,执行SQL语句
    4. 释放资源
  5. 实际操作示例代码

    public class MybatisDemo {
        public static void main(String[] args) throws IOException {
    
            //1.加载Mybatis配置文件,获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
            //2.获取SQLSession对象,来执行SQL语句
            SqlSession sqlSession = sqlSessionFactory.openSession();
    
            //3.执行sql语句
            List<User> users = sqlSession.selectList("Test.selectAll");
    
            System.out.println(users);
    
            //4.释放资源
            sqlSession.close();
        }
    }
    

4.Mapper代理开发

开发步骤

  1. 定义一个跟映射文件同名的Mapper接口,并且同目录下。

  2. 将映射文件的命名空间改成Mapper接口的路径

  3. 在Mapper中定义方法名和映射文件的SQL语句同名(方法名=id)保持返回值,参数类型相同。

  4. 配置文件(mybatis-config)的文件路径更改

    <mappers>
            <!--加载SQL映射文件-->
            <mapper resource="com/itpak/Mapper/UserMapper.xml"/>
        </mappers>
    
  5. 执行代码。

    1. 使用Session的getMapper方法获取Mapper接口代理对象。
    2. 调用sql方法执行方法。

5、配置文件完成增删改查

实现操作

  1. 编写接口方法 :Mapper接口(在接口中实现方法)
  2. 编写SQL语句:在SQL映射文件当中
  3. 执行

6、注意

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--Mapper代理的命名空间要设置Mapper的全路径-->
<mapper namespace="com.itpak.Mapper.UserMapper">
    <select id="selectAll" resultType="com.itpak.pojo.User">
        select * from user;
    </select>
</mapper>

resultType指的是表的实体类,例如user表的对应实体类user的路径

Mapper代理的命名空间要设置Mapper的全路径

pojo类的属性名必须与数据表中的属性名一样,不然查询结果为空

可以通过定义resultMap解决不同名的问题,column表示表中的列名,property表示pojo类中的属性名

 <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

7.类型别名(typeAliases)

  1. 注解使用在pojo实体类,配置文件当中的路径就是pojo包,需要在实体类之前添加注解@Alias("brand"),参数为别名

     <typeAliases>
            <package name="com.itpak.pojo"/>
        </typeAliases>
    
    @Alias("brand")
    public class Brand {
        private int id ;
    
  2. 若无注解,按照类名来命名

8.映射器(Mapper)

  1. 在Mybatis.xml文件中声明映射器去哪找SQL语句

    <mappers>
            <!--加载SQL映射文件-->
            <!--<mapper resource="com/itpak/Mapper/UserMapper.xml"/>-->
            
            <!--Mapper代理使用包扫描-->
            <package name="com.itpak.Mapper"/>
        </mappers>
    
  2. 使用包扫描可以在这个包下寻找类资源

9.注意要点

image-20230324114454453

10.多条件查询

  1. 使用@Param注解使用占位符

    List<Brand> selectByCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
    
  2. 创建一个对象来传递条件

    		int status=1;
            String companyName="华为";
            String brandName="华为";
    
            //处理参数
            companyName="%"+companyName+"%";
            brandName="%"+brandName+"%";
    
            Brand brand1=new Brand();
            brand1.setCompany_name(companyName);
            brand1.setBrand_name(brandName);
    
  3. 使用Map传递查询条件

    		int status=1;
            String companyName="华为";
            String brandName="华为";
    
            //处理参数
            companyName="%"+companyName+"%";
            brandName="%"+brandName+"%";	
    		Map map=new HashMap();
    
    		map.put("status",status);
    		map.put("companyName",companyName);
    		map.put("brandName",brandName);
    
  4. 注意:在进行模糊查询的时候,需要处理一下参数,不然查询结果可能会找不到

11.多条件动态查询

<select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <if test="status!=null and status!=-1">and status=#{status}</if>
            <if test="companyName!=null and companyName!=''">and company_name like #{companyName}</if>
            <if test="brandName!=null and brandName!=''"> and brand_name like #{brandName}</if>
        </where>
    </select>

使用if判断条件来实现动态SQL 为什么要使用where标签,主要因为status也有可能为空,在每个条件下都使用and的话就需要where标签

12.单条件的动态SQL

使用choose标签类似于Java中的Switch,when标签类似于java中的case,otherwise类似于java中的default

13.添加和修改

  1. 添加

    <insert id="add" useGeneratedKeys="true" keyProperty="id">/*设置主键返回*/
            insert into tb_brand (brand_name, company_name, ordered, des, status)
            values (#{brandName},#{companyName},#{ordered},#{des},#{status});
        </insert>
    

    主键返回需要设置 useGeneratedKeys="true" keyProperty="id"

    注意:需要提交事务才能在数据表中更新

            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //提交事务
            sqlSession.commit();
    

    两种方式提交事务。

  2. 修改

    动态修改使用if标签

     <update id="modify" >
            update tb_brand
            <set>
                <if test="status!=-1 and status!=null">status=#{status},</if>
                <if test="brandName!='' and brandName!=null">brand_name=#{brandName},</if>
                <if test="companyName!='' and companyName!=null">company_name=#{companyName},</if>
                <if test="ordered!=0 and ordered!=null">ordered=#{ordered},</if>
                <if test="des!='' and des!=null">des=#{des},</if>
            </set>
            where id=#{id}
        </update>
    

14.删除

  1. 删除一个

        <delete id="deleteById">
            delete
            from tb_brand
            where id=#{id};
        </delete>
    
  2. 删除多个-----使用foreach标签,需要使用@param标签命名ids

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

15.参数传递

注解@Param,相当于将args的键名替换掉了,不使用注解时,自动填充到argsMap集合当中在查询条件中可以使用

{args0}、#{args1}.......代替之前的注解开发,但是不推荐使用。不方便使用。

16.注解使用

@Select()
@Delete()
@Update()
@Insert()

注解开发一般使用在简单的SQL语句,而复杂的语句需要通过XML文件来编写