mybatis之注解实现CRUD功能

Posted cugb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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来代替注解。

以上是关于mybatis之注解实现CRUD功能的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis第三课 Java注解的方式操作CRUD

mybatis-注解实现crud

Mybatis注解CRUD

mybatis执行CRUD操作的两种方式配置和注解

阶段3 1.Mybatis_12.Mybatis注解开发_3 mybatis注解开发保存和更新功能

Mybatis之Mapper代理开发