总流程: 1.编写接口 2.编写对应的mapper中的sql语句 3.测试 1. namespace namespace中的包名要和Dao/Mapper中的接口保持一致! 2. select 选择,查询语句:
- id:就是对应的namespace中的方法名;
- resulType:sql语句执行的返回值!
- parameterType:参数类型
注意增删改需要提交事务!
userMapper.java接口:
package com.zuo.dao;
import com.zuo.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
userMapper.xml接口对应的mapper
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zuo.dao.UserMapper">
<select id="getUserList" resultType="com.zuo.pojo.User">select * from mybatis.user</select>
<select id="getUserById" parameterType="int" resultType="com.zuo.pojo.User">select * from user where id = #{id}</select>
<insert id="addUser" parameterType="com.zuo.pojo.User">insert into user (id,name,pwd) values (#{id},#{name},#{pwd})</insert>
<update id="updateUser" parameterType="com.zuo.pojo.User">update user set name=#{name},pwd=#{pwd} where id= #{id}</update>
<delete id="deleteUser" parameterType="int">delete from user where id=#{id}</delete>
</mapper>
UserMapperTest.java测试:
package com.zuo.dao;
import com.zuo.pojo.User;
import com.zuo.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 userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for(User user: userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int res = userMapper.addUser(new User(10, "afa", "123"));
if(res>0) {
System.out.println("插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.updateUser(new User(10, "haha", "12345"));
if(res>0) {
System.out.println("修改成功!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(10);
sqlSession.commit();
sqlSession.close();
}
}
|