<?xml version="1.0" encoding="utf-8" ?>
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.shangguan.mybatis.mapper.usermapper">
<resultmap id="baseresultmap" type="com.shangguan.mybatis.mapper.usermapper" >
<id column="id" property="id" jdbctype="bigint" />
<result column="username" property="username" jdbctype="varchar" />
<result column="password" property="password" jdbctype="varchar" />
</resultmap>
<!--查询所有-->
<select id="getall" resulttype="user">
select * from user
</select>
<!--保存用户-->
<insert id="saveuser" usegeneratedkeys="true" keyproperty="id">
insert into user(username,password) values(#{username},#{password})
</insert>
<!--通过id删除用户-->
<delete id="deleteuserbyid">
delete from user where id =#{id}
</delete>
<!--更新该用户信息-->
<update id="updateuser">
update user set username = #{username},password = #{password}
where id = #{id}
</update>
</mapper>
映射类usermapper.java:
@mapper
public interface usermapper {
public list<user> getall();
public void saveuser(user user);
public void deleteuserbyid(long id);
public void updateuser(@param("id") long id, @param("username") string username,
@param("password") string password);
}
public interface userservice {
public list<user> getalluser();
public void saveuser(user user);
public void deleteuserbyid(long id);
public void updateuser(long id, string username, string password);
}
userserviceimpl:
@service
public class userserviceimpl implements userservice {
@autowired
private usermapper usermapper;
@override
public list<user> getalluser() {
list<user> list = usermapper.getall();
return list;
}
@override
public void saveuser(user user) {
usermapper.saveuser(user);
}
@override
public void deleteuserbyid(long id) {
usermapper.deleteuserbyid(id);
}
@override
public void updateuser(long id, string username, string password) {
usermapper.updateuser(id, username, password);
}
}
7. controller层实现
usercontroller里面对接口进行封装:
@restcontroller
@springbootapplication
@requestmapping("/mybatis")
public class usercontroller {
@autowired
private userservice userservice;
@requestmapping("/getalluser")
public list<user> getalluser() {
list<user> list = userservice.getalluser();
return list;
}
@requestmapping("/saveuser")
public void saveuser(user user) {
userservice.saveuser(user);
}
@requestmapping("/deleteuserbyid")
public void deleteuserbyid(long id) {
userservice.deleteuserbyid(id);
}
@requestmapping("/updateuser")
public void updateuser(long id, string username, string password) {
userservice.updateuser(id, username, password);
}
}
8. 测试
启动spring boot项目,使用postman进行测试:
① http://localhost:8080/mybatis/getalluser 获取所有的用户信息
对比数据库无误:
② http://localhost:8080/mybatis/saveuser?username=啊哈&password=123321 添加一个名字为啊哈,密码为123321的用户
添加成功:
③ http://localhost:8080/mybatis/deleteuserbyid?id=6 删除id为6的用户