zoukankan      html  css  js  c++  java
  • mybatis之注解实现CRUD功能

    mybatis之注解实现CRUD功能

    步骤:

    1、根据表创建pojo类

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int uid;
        private String uname;
        private String upass;
    }
    

    2、创建接口,并用注解把sql语句写上

    public interface UserDao {
    
        @Select("select * from users")
        public ArrayList<User> getAllUser();
    
        @Insert("insert into users (uname,upass) values (#{user.uname},#{user.upass})")
        public void addUser(@Param("user") User user);
    
        @Update("update users set upass = #{upass} where uid = #{uid}")
        public void updatePass(@Param("uid") int uid,@Param("upass") String upass);
    }
    
    

    3、在mybatis-config。xml文件的mappers中映射接口

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

    4、测试

    public class UserDaoTest {
        @Test
        public void query(){
            SqlSession sqlSession = DbUtils.getSqlSession();
    
            UserDao userDao = sqlSession.getMapper(UserDao.class);
    
            userDao.addUser(new User(8,"yixiu","122456"));
    
            userDao.updatePass(7,"xiaofuzi");
    
            ArrayList<User> list = userDao.getAllUser();
    
    
            for (User user : list) {
                System.out.println(user);
            }
            sqlSession.commit();
            sqlSession.close();
        }
    }
    

    5、结果

    [com.cugb.dao.UserDao.addUser]-==>  Preparing: insert into users (uname,upass) values (?,?) 
    [com.cugb.dao.UserDao.addUser]-==> Parameters: yixiu(String), 122456(String)
    [com.cugb.dao.UserDao.addUser]-<==    Updates: 1
    [com.cugb.dao.UserDao.updatePass]-==>  Preparing: update users set upass = ? where uid = ? 
    [com.cugb.dao.UserDao.updatePass]-==> Parameters: xiaofuzi(String), 7(Integer)
    [com.cugb.dao.UserDao.updatePass]-<==    Updates: 1
    [com.cugb.dao.UserDao.getAllUser]-==>  Preparing: select * from users 
    [com.cugb.dao.UserDao.getAllUser]-==> Parameters: 
    [com.cugb.dao.UserDao.getAllUser]-<==      Total: 6
    User(uid=1, uname=chenjunwei, upass=111111)
    User(uid=2, uname=zhaojiu, upass=123456)
    User(uid=3, uname=lianguofeng, upass=123456)
    User(uid=4, uname=renpengyu, upass=820122)
    User(uid=7, uname=huangjian, upass=xiaofuzi)
    User(uid=8, uname=yixiu, upass=122456)
    

    说明注解起作用了。

    注解的可读性会比较高,省去了mapper.xml的文件,但在处理复杂的sql语句时会显得比较吃力。mybatis中还是建议使用mapper.xml来代替注解。

  • 相关阅读:
    1029. Two City Scheduling
    JS判断Android、iOS或浏览器的多种方法(四种方法)【转】
    layui select onchange事件【转】
    PHP 判断数据类型【转】
    php 对数组进行排序【转】
    php中怎么删除数组的第一个元素和最后一个元素【转】
    php数组操作之获取数组元素索引(键)值【转】
    HTML表单中 textarea标签的value属性赋值【转】
    为什么js的"关联数组"不能转成json字符串而对象可以?【转】
    CSS white-space属性是用来设置如何处理元素中的空白【转】
  • 原文地址:https://www.cnblogs.com/cugb/p/13268578.html
Copyright © 2011-2022 走看看