CRUD(Mybatis注解开发)

suaxi
2020-12-13 / 0 评论 / 78 阅读 / 正在检测是否收录...

CRUD(Mybatis注解)

1、在创建工具类时可以设置自动提交事务

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

2、接口

package com.sw.dao;

import com.sw.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * @Author suaxi
 * @Date 2020/12/11 17:00
 */
public interface UserMapper {

    //删除用户
    @Delete("delete from user where id = #{uid}")
    int deleteUserById(@Param("uid")int id);

    //根据id查询
    //注意:有多个参数时必须加上@Param("")注解
    //例:根据id和用户名查询
    //User finUser(@Param("id")int id,@Param("username")String name)
    @Select("select * from user where id = #{id}")
    User findUserById(@Param("id")int id);

    //查询所有用户
    @Select("select * from user")
    List<User> findUser();
}

3、测试类

package com.sw;

import com.sw.dao.UserMapper;
import com.sw.pojo.User;
import com.sw.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @Author suaxi
 * @Date 2020/12/12 21:49
 */
public class UserMapperTest {

    @Test
    public void findUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        List<User> userList = mapper.findUser();
//        for (User user : userList) {
//            System.out.println(user);
//        }
//        User user = mapper.findUserById(1);
//        System.out.println(user);
        mapper.deleteUserById(4);
        sqlSession.close();

    }
}

4、注:在mybatis-config.xml中必须注册绑定接口

<mappers>
    <mapper class="com.sw.dao.UserMapper"/>
</mappers>

5、关于@Parm()注解

  • 基本类型的参数String类型需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话可以忽略(本身就只有它一个值)
  • 在SQL中引用的就是@Param()中设定的属性名

6、#{}${}的区别

#{}

  • 采用预编译的方式,相当于JDBC的占位符PreparedStatement
  • 一个#{}就是一个占位符
  • Mybatis在为#{}设置值时会加引号

${}

  • 采用直接拼接的方式,不对数值做预编译
  • Mybatis在为${}设置值时不加引号
  • 存在sql注入的问题
0

评论 (0)

取消