参数:
id | 对应namespace也就是接口中的方法名 |
---|---|
resultType | SQL语句的返回值类型 |
parameterType | 参数类型 |
1.接口中写addUser方法
public interface UserMapper {
// 查询所有的用户
List<User> getUserList();
// 根据id查找用户
User getUserByID(int id);
//添加用户
int addUser(User user);
}
2.userMapper.xml里写insert标签
<insert id="addUser" parameterType="com.wang.pojo.User">
insert into mybatis.user (id,name ,pwd) values (#{
id},#{
name},#{
pwd})
</insert>
3.Junit测试
@Test
public void addUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int lisa = mapper.addUser(new User(4, "lisa", "79465465"));
if (lisa>0){
System.out.println("添加成功");
}
sqlSession.commit();
sqlSession.close();
}
1.接口内写方法
// 修改用户
int updateUser(User user);
2.mybatis-config.xml写操作
<update id="updateUser" parameterType="com.wang.pojo.User" >
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id} ;
update>
3.Junit测试
@Test
public void update(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.updateUser(new User(2, "张三", "123458"));
if (row>0){
System.out.println("更新成功!");
}
sqlSession.commit();
sqlSession.close();
}
1.接口内写方法
// 删除用户
int deleteUser(int id);
2.mybatis-config.xml写操作
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
delete>
3.Junit测试
@Test
public void deleteUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.deleteUser(4);
if (row>0){
System.out.println("删除成功!");
}
sqlSession.commit();
sqlSession.close();
}
场景:实体类,数据库中的字段或者表,参数过多的时候可以考虑使用map
方法一样:
1.接口写方法
// 用map方式添加用户
int insertUser(Map<String,Object> map);
2 mybatis-config.xml写sql语句
<insert id="insertUser" parameterType="map">
insert into mybatis.user (id,name ,pwd) values (#{
mapId},#{
mapName},#{
mapPwd});
</insert>
3.测试
@Test
public void insertUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("mapId",4);
map.put("mapName","lisa1");
map.put("mapPwd","1745289");
int row = mapper.insertUser(map);
if (row>0){
System.out.println("添加成功!");
}
sqlSession.commit();
sqlSession.close();
}
1.接口写方法
// 模糊查询
List<User> getUserBYLike(String value);
2 mybatis-config.xml写sql语句
<select id="getUserBYLike" resultType="com.wang.pojo.User">
select * from mybatis.user where name like "%"#{
value}"%";
</select>
3.测试
@Test
public void getUserByLike(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserBYLike("李");
for (User user:
userList) {
System.out.println(user);
}
sqlSession.close();
}