1.编写接口
package com.zzqsmile.dao;
import com.zzqsmile.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> getUsers();
//方法存在多个参数,所有的参数前必须要加@Param()
@Select("select * from mybatis.user where id =#{id}")
User getUserById(@Param("id") int id);
//增加用户
@Insert("insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd})")
int userAdd(User user);
//修改用户
@Update("update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}")
int userUpd(User user);
//删除用户
@Delete("delete from mybatis.user where id = #{uid}")
int userDel(@Param("uid")int id);
}
2.绑定接口
<!-- 绑定接口-->
<mappers>
<mapper class="com.zzqsmile.dao.UserMapper"></mapper>
</mappers>
3.编写测试类
package com.zzqsmile.dao;
import com.zzqsmile.pojo.User;
import com.zzqsmile.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
}
@Test
public void userAdd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.userAdd(new User(6,"张三丰","123321"));
if (i>0){
System.out.println("添加成功");
}
}
@Test
public void userUpd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.userUpd(new User(6,"张三丰","999999"));
if (i>0){
System.out.println("修改成功");
}
}
@Test
public void userDel(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.userDel(5);
if (i>0){
System.out.println("删除成功");
}
}
}
@Param()注意点
- 基本类型或String类型要加上
- 引用类型不需要加
- 如果只有1个基本类型可以省略,但是建议添加
网友评论