实现增删改查
- namespace
namespace中的包名要和接口的包名一致
select
- id :就是对应namespace中的方法名
- resultType :SQL语句的返回值
- parameterType: 参数类型
编写接口
public interface UserDao {
//获取全部用户
List<User> getUserList();
//根据id查询
User getUserById(int id);
//增加一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
编写mapper中的sql
<mapper namespace="com.skl.dao.UserDao">
<select id="getUserList" resultType="com.skl.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.skl.pojo.User">
select * from mybatis.user where id= #{id}
</select>
<insert id="addUser" parameterType="com.skl.pojo.User">
insert into mybatis.user (id,`name`,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.skl.pojo.User">
update mybatis.user set pwd = #{pwd} where id = #{id}
</update>
<delete id="deleteUser" parameterType="com.skl.pojo.User">
delete from mybatis.user where id = #{id}
</delete>
</mapper>
测试
@Test
public void test05(){
SqlSession sqlSession = null;
try {
//获取sqlseaaion对象
sqlSession = MybatisUtils.getSqlSession();
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
int res = userDao.deleteUser(1010);
if (res>0){
System.out.println("delete success");
}
//提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}