• mybatis通过注解完成数据库操作(不适用xml配置)


    mybatis-config.xml中绑定接口

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

    UserMapper.java中写CRUD

    package dao;
    
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import org.junit.Test;
    import pojo.User;
    
    import java.util.HashMap;
    import java.util.List;
    
    public interface UserMapper {
        //需要在核心配置文件绑定
        @Select("select * from user")
        List<User> getUser();
    
        //方法存在多个参数,所有的参数前面最好加上@Param注解,注解的内容将决定另一个参数
        @Select("select * from user where id = #{id}")
        User getUserById(@Param("id") int id);
    
    
    }

    UserDaoTest中测试

    package dao;
    
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.session.RowBounds;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.log4j.Logger;
    import org.junit.Test;
    import pojo.User;
    import utils.MybatisUtils;
    
    import java.util.HashMap;
    import java.util.List;
    
    
    public class UserDaoTest {
    
        @Test
        public void test()
        {
            SqlSession sqlSession=MybatisUtils.getSqlSession();
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
    
            List<User> userList = userMapper.getUser();
            for (User user : userList) {
                System.out.println(user.getName());
            }
            sqlSession.close();
        }
        @Test
        public void testByID()
        {
            SqlSession sqlSession=MybatisUtils.getSqlSession();
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            User user=userMapper.getUserById(3);
            System.out.println(user.getName());
            sqlSession.close();
        }
    
    
    
    
    }

  • 相关阅读:
    C++笔记 谓词 1
    win7 ipv6设置(isatap)
    C++笔记
    打水印
    jquery导航滚动固定在顶部
    javascript获得属性
    tr光棒效果
    按字母查找
    js购物车
    数据采集
  • 原文地址:https://www.cnblogs.com/yizhixiaozhu/p/14674404.html
Copyright © 2020-2023  润新知