其他分享
首页 > 其他分享> > 040_Mybatis注解开发

040_Mybatis注解开发

作者:互联网

目录

使用注解开发

image.png

mybatis-config.xml中注册接口

    <mappers>
        <!--绑定接口-->
        <mapper class="com.qing.dao.UserMapper"/>
    </mappers>

Mapper接口中添加注解

package com.qing.dao;

import com.qing.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

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

/**
 * 接口
 */
public interface UserMapper {

    /**
     * 查询全部用户
     *
     * @return
     */
    @Select("select * from mybatis.user")
    List<User> getUserList();

    /**
     * 根据ID查询用户
     *
     * @param id
     * @return
     */
    @Select("select * from mybatis.user where id=#{userId} ")
    User getUserById(@Param("userId") int id);

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Insert("insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})")
    int insert(User user);
}

测试

package com.qing.dao;

import com.qing.pojo.User;
import com.qing.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    /**
     * 查询全部用户
     */
    @Test
    public void getUserList() {
        SqlSession sqlSession = null;
        try {
            // 获取sqlSession
            sqlSession = MybatisUtils.getSqlSession();
            // 执行SQL
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭sqlSession
            sqlSession.close();
        }
    }

    /**
     * 根据ID查询用户
     */
    @Test
    public void getUserById() {
        SqlSession sqlSession = null;
        try {
            // 获取sqlSession
            sqlSession = MybatisUtils.getSqlSession();
            // 执行SQL
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭sqlSession
            sqlSession.close();
        }
    }
}

image.png

sqlSession设置自动提交

image.png

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

@Param()注解

标签:SqlSession,User,sqlSession,user,import,Mybatis,注解,040
来源: https://www.cnblogs.com/wl3pb/p/14999220.html