07-mybatis中使用注解进行增删改查

1. 准备工作

新建一个maven项目和数据库表,文件包括:

  • 实体类
  • mapper接口
  • 工具类
  • mybatis的配置文件
  • 测试类
  • pom.xml文件

在这里插入图片描述

2. 更改文件,使用注解进行增删改查

以下4个文件,配置好后,就不需要再改动

  • 实体类
package com.mybatis.entity;

import lombok.Data;

/**
 * @Description 实体类
 * @ClassName User
 * @Author yuhuofei
 * @Date 2021/11/14 0:52
 * @Version 1.0
 */
@Data
public class UserEntity {
    private int id;
    private String name;
    private String password;
}

  • mybatis-config.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>

    <!--从外部文件中读取配置-->
    <properties resource="application.properties"/>

    <!--一些基础设置-->
    <settings>
        <setting name="cacheEnabled" value="true"/>                 <!--常用,开启缓存-->
        <setting name="lazyLoadingEnabled" value="true"/>           <!--常用,懒加载-->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>               <!--常用,自动生成列-->
        <setting name="useGeneratedKeys" value="false"/>            <!--有时用,自动生成主键-->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25"/>
        <setting name="defaultFetchSize" value="100"/>
        <setting name="safeRowBoundsEnabled" value="false"/>
        <setting name="mapUnderscoreToCamelCase" value="false"/>    <!--常用,驼峰转换-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>            <!--常用,日志打印-->
        <setting name="localCacheScope" value="SESSION"/>
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    </settings>

    <typeAliases>
        <package name="com.mybatis.entity"/>
    </typeAliases>

    <!--环境的配置,默认是development,可以配置多个-->
    <environments default="development">
        <!--development环境配置-->
        <environment id="development">
            <!--事务管理,默认用jdbc的事务管理-->
            <transactionManager type="JDBC"/>
            <!--数据源配置-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置mapper.xml文件,进行注册-->
    <mappers>
        <mapper class="com.mybatis.mapper.UserEntityMapper"/>
    </mappers>

</configuration>
  • 工具类
package com.mybatis.utils;

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;

/**
 * @Description 工具类
 * @ClassName User
 * @Author yuhuofei
 * @Date 2021/11/14 0:52
 * @Version 1.0
 */
public class NewMybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //先获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //获取SqlSession实例,SqlSession完全包含了面向数据库执行SQL命令所需的所有方法

    public static SqlSession getSqlSession() {
        //参数true,表示自动提交事务
        return sqlSessionFactory.openSession(true);
    }
}

  • pom.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">
    <parent>
        <artifactId>spring-boot-study</artifactId>
        <groupId>org.person</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>02-mybatis</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <!--在build中,配置resources,防止资源被过滤,导致导出失败-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>
2.1 实现查询

(1)在mapper接口中,新增一个查询方法,如下所示:

package com.mybatis.mapper;

import com.mybatis.entity.UserEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * @Description User接口
 * @InterfaceName UserMapper
 * @Author yuhuofei
 * @Date 2021/11/14 0:55
 * @Version 1.0
 */
public interface UserEntityMapper {

    //通过id查询
    @Select("select * from user where id  =#{id}")
    UserEntity getUserById(@Param("id") Integer id);

}

(2)在测试类中,调用mapper接口中的方法,如下所示:

package com.mybatis.entity;

import com.mybatis.mapper.UserEntityMapper;
import com.mybatis.utils.NewMybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * @Description 测试User
 * @ClassName UserTest
 * @Author yuhuofei
 * @Date 2021/11/14 1:19
 * @Version 1.0
 */
public class NewUserTest {

    @Test
    public void getUser() {
        //获取SqlSession对象
        SqlSession sqlSession = NewMybatisUtils.getSqlSession();

        UserEntityMapper mapper = sqlSession.getMapper(UserEntityMapper.class);
        UserEntity user = mapper.getUserById(2);
        System.out.println("得到的结果是:" + user);

        //关闭sql连接
        sqlSession.close();
    }
}

(3)运行测试类,结果如下:

在这里插入图片描述

2.2 实现新增

(1)在mapper接口中,新增以下方法:

    @Insert("insert into user(id,name,password) values(#{id},#{name},#{password})")
    Integer insertUser(UserEntity userEntity);

(2)测试类中,新增调用的方法

@Test
    public void insertUser() {
        //获取SqlSession对象
        SqlSession sqlSession = NewMybatisUtils.getSqlSession();

        UserEntityMapper mapper = sqlSession.getMapper(UserEntityMapper.class);
        UserEntity userEntity = new UserEntity();
        userEntity.setId(6);
        userEntity.setName("小明");
        userEntity.setPassword("658497");

        int res = mapper.insertUser(userEntity);
        System.out.println("得到的结果是:" + res);

        //关闭sql连接
        sqlSession.close();
    }

(3)测试结果

在这里插入图片描述

2.3 实现删除

(1)在mapper接口中,新增以下方法:

    @Delete("delete from user where id = #{id}")
    Integer deleteUser(@Param("id") Integer id);

(2)测试类中,新增调用的方法

    @Test
    public void deleteUser() {
        //获取SqlSession对象
        SqlSession sqlSession = NewMybatisUtils.getSqlSession();

        UserEntityMapper mapper = sqlSession.getMapper(UserEntityMapper.class);
        Integer result = mapper.deleteUser(6);
        System.out.println("得到的结果是:" + result);

        //关闭sql连接
        sqlSession.close();
    }

运行测试方法,即可得到结果

2.4 实现修改

(1)在mapper接口中,新增以下方法:

    @Update("update user set name = #{name} where id = #{id}")
    Integer updateUser(@Param("id") Integer id,@Param("name") String name);

(2)测试类中,新增调用的方法

    @Test
    public void updateUser() {
        //获取SqlSession对象
        SqlSession sqlSession = NewMybatisUtils.getSqlSession();

        UserEntityMapper mapper = sqlSession.getMapper(UserEntityMapper.class);
        Integer result = mapper.updateUser(5,"赵六");
        System.out.println("得到的结果是:" + result);

        //关闭sql连接
        sqlSession.close();
    }

运行测试方法,即可实现修改。

3. 关于@Param注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型,可以忽略,但建议加上
  • 在SQL中,引用的就是通过@Param设定的属性名
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值