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