Mybatis:实现“增删改查”

Posted _GGBond_

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis:实现“增删改查”相关的知识,希望对你有一定的参考价值。

Mybatis(二):实现“增删改查”



前言

本博主将用CSDN记录软件开发求学之路上亲身所得与所学的心得与知识,有兴趣的小伙伴可以关注博主!也许一个人独行,可以走的很快,但是一群人结伴而行,才能走的更远!

一、MyBatis的增删改查

1、添加

UserMapper接口:

     /**
     *添加用户信息
     */
    int insertUser();

UserMapper.xml

<!--int insertUser();-->
          <insert id="insertUser">
                insert into t_user values(null,'张三','123',23,'女')
          </insert>

2、修改

UserMapper接口:

     /**
     * 修改用户信息
     */
    void updateUser();

UserMapper.xml

        <!-- void updateUser();-->
        <update id = "updateUser">
             update t_user set username = '张三' where id = 4
        </update>

3、删除

UserMapper接口:

    /**
     * 删除用户信息
     */
    void deleteUser();

UserMapper.xml

        <!-- void deleteUser();-->
        <delete id="deleteUser">
             delete from t_user where id = 5
        </delete>

4、查询

4.1 查询一个实体

UserMapper接口:

    /**
     * 查询用户信息
     */
    User getUserId();
UserMapper.xml
      <!--User getUserById();-->
        <!--
            查询功能的标签必须设置resultType或resultMap
            resultType:设置默认的映射关系
            resultMap:设置自定义的映射关系
        -->
    <select id="getUserById" resultType="com.ir.mybaits.pojo.User">
          select * from t_user where id = 3
     </select>
     

4.1 查询集合

UserMapper接口:

    /**
     * 查询用户信息
     */
    List<User> getAllUser();

UserMapper.xml

      <!--List<User> getAllUser();-->
    <select id="getAllUser" resultType="User">
        select * from t_user
    </select>

注意:

⭕ 查询的标签select必须设置属性resultTyperesultMap,用于设置实体类和数据库表的映射关系
resultType:自动映射,用于属性名和表中字段名一致的情况
resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况

⭕当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常TooManyResultsException,但是若查询的数据只有一条,可以使用实体类或集合作为返回值

二、MyBatis获取参数值的两种方式(重点)

MyBatis获取参数值的两种方式:$#

$的本质就是字符串拼接,使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;

#的本质就是占位符赋值,但是#使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号

1、单个字面量类型的参数

⭕ 若mapper接口中的方法参数为单个的字面量类型,此时可以使用$#以任意的名称获取参数的值,但是需要注意$的单引号问题

⭕ 代码演示:

UserMapper

/**
     * @description:查询用户信息
     * @author: Hey
     * @date: 2022/7/3 16:53
     * @param: [username]
     * @return: com.ir.mybatis.pojo.User
     **/
    User getUserByUsername(String username);

UserMapper.xml

 <!--User getUserByUsername(String username);-->
    <select id="getUserByUsername" resultType="user">
         <!--此时只注重传递过来的值,username中的usernsme可以替换为任意字母,结果都不会改变-->
          <!--select * from t_user where username = '$username';-->
          select * from t_user where username = #username;
    </select>

UserMapperTest

   /**
    * @description:
    * @author: Hey
    * @date: 2022/7/3 15:29
    * @param: []
    * @return: void
    **/
    @Test
    public void getUserByUsername()
        UserMapper userMapper = SqlSessionUtils.getSqlSession().getMapper(UserMapper.class);
        System.out.println(userMapper.getUserByUsername("张三"));
    

2、多个字面量类型的参数

mapper接口方法的参数为多个时,此时MyBatis会将这些参数放在一个map集合中,以两种方式进行存储

  1. arg0,arg1…为键,以参数为值
  2. param1,param2…为键,以参数为值

因此只需要通过$#访问map集合的键就可以获取相对应的 值,但是需要注意$的单引号问题。

⭕ 代码演示:

UserMapper

    /**
     * @description:检查用户登录信息
     * @author: Hey
     * @date: 2022/7/3 15:46
     * @param: [username, password]
     * @return: com.ir.mybatis.pojo.User
     **/
    User checkLoginByParameter(String username,String password);

UserMapper.xml

  <!--User checkLoginByParameter(String username,String password);-->
    <select id="checkLoginByParameter" resultType="user">
        select * from t_user where username=#arg0 and password=#arg1;
    </select>

UserMapperTest

 /**
     * @description:
     * @author: Hey
     * @date: 2022/7/3 15:30
     * @param: []
     * @return: void
     **/
    @Test
    public void checkLoginByParam()
         UserMapper userMapper = SqlSessionUtils.getSqlSession().getMapper(UserMapper.class);
         User user = userMapper.checkLoginByParameter("张三","123");
        System.out.println(user);
    

3、map集合类型的参数

⭕ 若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中,只需要通过$#访问map集合的键就可以获取相对应的值,但是需要注意$的单引号问题

⭕ 代码演示:

UserMapper

    /**
     * @description:通过自定义Map来验证登录
     * @author: Hey
     * @date: 2022/7/3 15:45
     * @param:
     * @return:
     **/
    User checkLoginByMap(Map<String, Object> map);

UserMapper.xml

 <!--User checkLoginByMap(Map<String, Object> map);-->
    <select id="checkLoginByMap" resultType="user">
        select * from t_user where username=#username and password=#password;
    </select>

UserMapperTest

     /**
     * @description:测试通过自定义Map验证登录
     * @author: Hey
     * @date: 2022/7/3 15:55
     * @param: []
     * @return: void
     **/
    @Test
    public void checkLoginByMap()
        UserMapper userMapper = SqlSessionUtils.getSqlSession().getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap<>();
        map.put("username","张三");
        map.put("password","123");
        User user = userMapper.checkLoginByMap(map);
        System.out.println(user);
    

4、实体类类型的参数

⭕ 若mapper接口中的方法参数为实体类对象时,此时可以使用$#,通过访问实体类对象中的属性名获取属性值,但是需要注意$的单引号问题

⭕ 代码演示:

UserMapper

 /**
     * @description:添加用户
     * @author: Hey 
     * @date: 2022/7/3 16:11
     * @param: [user]
     * @return: int
     **/
    Integer insertUser(User user);

UserMapper.xml

<!--int insertUser(User user);-->
    <select id="insertUser" >
        insert into t_user values(null,#username,#password,#age,#sex,#email)
    </select>

UserMapperTest

     /**
     * @description:添加用户  
     * @author: Hey
     * @date: 2022/7/3 16:24
     * @param: []
     * @return: void
     **/
    @Test
    public void insertUser()
        UserMapper userMapper = SqlSessionUtils.getSqlSession().getMapper(UserMapper.class);
        Integer result = userMapper.insertUser(new User(null,"喜羊羊","123456",18,"男","123123@qq.com"));
        System.out.println(result);
    

5、使用@Param标识参数

⭕ 可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中,以如下两种方式来取值访问:

  1. @Param注解的value属性值为键,以参数为值;
  2. param1,param2…为键,以参数为值;

只需要通过$#访问map集合的键就可以获取相对应的值,但是需要注意$的单引号问题

⭕ 代码演示:

UserMapper

 /**
     * @description:通过参数注解验证登录
     * @author: Hey 
     * @date: 2022/7/3 16:59
     * @param: [username, password]
     * @return: com.ir.mybatis.pojo.User
     **/
    User checkLoginByParam(@Param("username") String username, @Param("password") String password);

UserMapper.xml

    <!--User checkLoginByParam(@Param("username") String username, @Param("password") String password);-->
    <select id="checkLoginByParam" resultType="User">
        select * from t_user where username = #username and password = #password
    </select>

UserMapperTest

 /**
     * @description:通过注解方式验证登录
     * @author: Hey
     * @date: 2022/7/3 16:57
     * @param: []
     * @return: void
     **/
    @Test
    public void testCheckLoginByParam()
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.checkLoginByParam("admin", "123456");
        System.out.println(user);
    

6、结论

将以上五种情况分为两类情况
⭕ 情况一:参数为实体类型
⭕ 情况二:参数都用@Param来修饰

三、MyBatis的各种查询功能

1、查询一个实体类对象

SelectMapper

    /**
     * @description:通过id查询用户
     * @author: Hey
     * @date: 2022/7/3 17:54
     * @param: [id]
     * @return: com.ir.mybatis.pojo.User
     **/
    User getUserById(@Param("id") Integer id);

SelectMapper.xml

<select id="getUserById" resultType="user">
         select * from t_user where id= #id;
    </select>

SelectMapperTest

/**
     * @description:通过id查询用户
     * @author: Hey
     * @date: 2022/7/3 17:58
     * @param: []
     * @return: void
     **/
    @Test
    public void getUserById()
        SelectMapper selectMapper = SqlSessionUtils.getSqlSession().getMapper(SelectMapper.class);
        User user = selectMapper.getUserById(3);
        System.out.println(user);
    

2、查询一个list集合

SelectMapper

/**
     * @description:获取多个用户
     * @author: Hey
     * @date: 2022/7/3 17:56
     * @param: []
     * @return: java.util.List<com.ir.mybatis.pojo.User>
     **/
    List<User> getAllUser();

SelectMapper.xml

<select id="getAllUser" resultType="user">
        select * from t_user;
    </select>

SelectMapperTest

/**
     * @description:查询所有用户
     * @author: Hey
     * @date: 2022/7/3 18:00
     * @param: []
     * @return: void
     **/
    @Test
    public void getAllUser()
        SelectMapper selectMapper = SqlSessionUtils.getSqlSession().getMapper(SelectMapper.class);
        List<User> list =  selectMapper.getAllUser();
        for (User user:list
             ) 
            System.out.println(user);
        
    

3、查询单个数据

MyBatis中,对于Java中常用的类型都设置了类型别名

AliasMapped Type
_bytebyte
_char (since 3.5.10)char
_character (since 3.5.10)char
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
char (since 3.5.10)Character
character (since 3.5.10)Character
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
bigintegerBigInteger
objectObject
date[]Date[]
decimal[]BigDecimal[]
bigdecimal[]BigDecimal[]
biginteger[]BigInteger[]
object[]Object[]
mapMap
hashmapHashMap
listList
arraylistArrayList
collectionCollection
iteratorIterator

SelectMapper

    /**
     * @description:查询用户信息的总记录数
     * @author: Hey
     * @date: 2022/7/3 20:40
     * @param: []
     * @return: java.lang.Integer
     **/
    Integer getCount();

SelectMapper.xml

 <select id="getCount" resultType="int">
        select count(1) from t_user;
    </select>

SelectMapperTest

/**
     * @description:查询用户信息的总记录数
     * @author: Hey 
     * @date: 2022/7/3 20:45
     * @param: []
     * @return: void
     **/
    @Test
    public void getCount()
        SelectMapper selectMapper = SqlSessionUtils.getSqlSession().getMapper(SelectMapper.class);
        int result = selectMapper.getCount();
        System.out.println(result);
    

4、查询一条数据为map集合

SelectMapper

/**
     * @description:根据id查询用户信息为一个map集合
     * @author: Hey
     * @date: 2022/7/3 20:59
     * @param: [id]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     **/
    Map<String,Object> getUserByIdToMap(@Param"id"Integer id);

SelectMapper.xml

<select id="getUserByIdToMap" resultType="map">
        select * from t_user where id=#id
</select>

SelectMapperTest

/**
     * @description:根据id查询用户信息为一个map集合
     * @author: Hey
     * @date: 2022/7/3 21:03
     * @param: []
     * @return: void
     **/
    @Test
    public void getUserByIdToMap()
        SelectMapper selectMapper = SqlSessionUtils.getSqlSession().getMapper(SelectMapper.class);
        System.out.println(selectMapper.getUserByIdToMap(5));
        //password=123456, sex=男, id=5, age=18, email=123123@qq.com, username=喜羊羊
    

5、查询多条数据为map集合

方式一:
SelectMapper

/**
     * @description:查询所有用户信息为Map集合
     * 
     * 将表中的数据以map集合的方式查询,一条数据对应一个map;
     * 若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
     * 
     * @author: Hey
     * @date: 2022/7/3 21:15
     * @param: []
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    List<Map<String, Object>> getAllUserToMap();    

SelectMapper.xml

 <select id="getAllUserToMap" resultType="map">
         select * from t_user
    </select>

SelectMapperTest

/**
     * @description:查询所有用户信息为Map集合
     * @author: Hey
     * @date: 2022/7/3 21:17
     * @param: []
     * @return: void
     **/
@Test
    public void testGetAllUserToMap()
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
        System.out.println(mapper.getAllUserToMap());
        /**
         * [password=123, sex=女, id=1, age=23, email=12345@qq.com, username=张三,
         * password=123456, sex=男, id=2, age=18, email=123123@qq.com, username=喜羊羊]
        */
    

方式二:
SelectMapper

/**
     * @description:查询所有用户信息为Map集合
     * 
     * 将表中的数据以map集合的方式查询,一条数据对应一个map;
     * 若有多条数据,就会产生个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
     * 
     * @author: Hey
     * @date: 2022/7/3 21:15
     * @param: []
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
   @MapKey("id")
    Map<String, Object> getAllUserToMap();    

SelectMapper.xml

 <select id="getAllUserToMap" resultType="map">
         select * from t_user
    </select>

SelectMapperTest

 /**
     * @description:查询所有用户信息为Map集合
     * @author: Hey
     * @date: 2022/7/3 21:17
     * @param: []
     * @return: void
     **/
    @Test
    public void testGetAllUserToMap()
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
        System.out.println(mapper.getAllUserToMap());
        /**
         * 
         * 1=password=123, sex=女, id=1, age=23, email=12345@qq.com, username=张三, 
         * 2=password=123456, sex=男, id=2, age=18, email=123123@qq.com, username=喜羊羊
         * 
        */
    

6、结论

MyBatis的各种查询功能:

⭕ 若查询出的数据只有一条
● 可以通过实体类对象接收
● 可以通过list集合接收
● 可以通过map集合接收
结果:
password=123456, sex=男, id=3, age=23, email=12345@qq.com, username=admin

⭕ 若查询出的数据有多条
● 可以通过实体类类型的list集合接收
● 可以通过map类型的list集合接收
●可以在mapper接口的方法上添加@MapKey注解,此时就可以将每条数据转换的map集合作为值,以某个字段的值作为键,放在同一个map集合中

⭕ 注意:一定不能通过实体类对象接收,此时会抛异常TooManyResultsException

MyBatis注解(@)实现增删改查

MyBatis注解(@)实现增删改查

# crud
# 名称不一致
	@Select("select * from book where id = #id")
	@Results(
		@Result(property="id",column="id",id=true),
		@Result(property="name",column="b_name"),
		@Result(property="createTime",column="b_create_time"),
		@Result(property="price",column="price")
	)
	public Book findById(int id);

# 一对一
@Select("select * from chapter")
	@Results( 
		@Result(property = "id", column = "id",id=true),
		@Result(property = "name", column = "name"),
		@Result(property = "bookId", column = "book_id"),
		@Result(property = "book",column="book_id",one = @One(fetchType=FetchType.EAGER,select="com.zhiyou100.mapper.BookMapper.findById"))
	)
	public List<Chapter> findAll();

# 一对多
	@Select("select * from book")
	//解决数据库和java属性不一致
	//property:java属性
	//column:数据库属性
	//id:判断是否是主键
	@Results(
		@Result(property="id",column="id",id=true),
		@Result(property="name",column="b_name"),
		@Result(property="createTime",column="b_create_time"),
		@Result(property="price",column="price"),
		@Result(property="chapters",column="id",many=@Many(fetchType=FetchType.EAGER,select="com.zhiyou100.mapper.ChapterMapper.findByBookId"))
	)
	public List<Book> findAll();


# 多对多
	@Select("select * from user")
	@Results(
		@Result(property="id",column="id",id=true),
		@Result(property="roles",column="id",many=@Many(fetchType=FetchType.EAGER,select="com.zhiyou100.mapper.RoleMapper.findByUserId"))	
	)
	public List<User> findUserAndRole();
		@Select("SELECT * from role r INNER JOIN  user_role ur ON r.id = ur.role_id where ur.user_id = #userId")
	public List<Role> findByUserId(int userId);

package com.prms.project.mapper;

import com.prms.project.domain.ProElement;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author CaoPengCheng
 * @version 1.0
 * @date 2021/11/14 19:47
 */
@Mapper
public interface ProElementMapper 
   
    @Results(
            @Result(property = "elementId", column = "element_id", id = true),
            @Result(property = "elementName", column = "element_name"),
            @Result(property = "orderNum", column = "order_num"),
            @Result(property = "component", column = "component"),
            @Result(property = "status", column = "status"),
            @Result(property = "createBy", column = "create_by"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateBy", column = "update_by"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "remark", column = "remark")
    )
    @Select("select element_id, element_name, order_num, component, status, create_time from prms_element order by order_num")
    List<ProElement> selectElementList();

    @Results(
            @Result(property = "elementId", column = "element_id", id = true),
            @Result(property = "elementName", column = "element_name"),
            @Result(property = "orderNum", column = "order_num"),
            @Result(property = "component", column = "component"),
            @Result(property = "status", column = "status"),
            @Result(property = "createBy", column = "create_by"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateBy", column = "update_by"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "remark", column = "remark")
    )
    @Select("select element_id, element_name, order_num, component, status, create_time " +
            "from prms_element " +
            "order by order_num" +
            "where element_id = #element_id")
    ProElement selectElementById(@Param("element_id") Long element_id);
    
    
    @Insert("insert into prms_element(element_name,order_num,component,status,create_by,create_time) " +
            "VALUES('#element_name',#order_num,'#component',#status,'#create_by','#create_time')")
    int  insertElement(
            @Param("element_name") String element_name,
            @Param("order_num") int order_num,
            @Param("component") String component,
            @Param("status") int status,
            @Param("create_by") String create_by,
            @Param("create_time") String create_time
    );

    @Update("UPDATE prms_element" +
            "set element_name='#element_name'," +
            "order_num=#order_num," +
            "component='#component'," +
            "status=#status," +
            "update_by='#update_by'," +
            "update_time='#update_time'" +
            "where element_id =  #element_id ")
    int updateElement(
            @Param("element_id") Long element_id,
            @Param("element_name") String element_name,
            @Param("order_num") int order_num,
            @Param("component") String component,
            @Param("status") int status,
            @Param("update_by") String update_by,
            @Param("update_time") String update_time
    );

    @Delete("delete from prms_element where element_id =  #element_id")
    int deleteElementById(@Param("element_id") Long element_id);
    


以上是关于Mybatis:实现“增删改查”的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis:实现“增删改查”

[mybatis]快速搭建一个mybatis程序,实现对数据的增删改查

mybatis怎么进行增删改查

mybatis生成的增删改查怎么用

Mybatis实现单表增删改查操作

Mybatis入门增删改查