码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis之注解实现CRUD功能

时间:2020-07-08 19:45:20      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:lang   set   private   integer   uid   ==   映射   utils   into   

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来代替注解。

mybatis之注解实现CRUD功能

标签:lang   set   private   integer   uid   ==   映射   utils   into   

原文地址:https://www.cnblogs.com/cugb/p/13268578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!