利用Mapper接口实现数据的增删改查
重要的一点就是划线部分的命名需要有对应关系,其他的都没有变化,比如
User.java
package com.pojo; public class User { private Integer id; private String lastName; private Integer sex; public User(Integer id, String lastName, Integer sex) { super(); this.id = id; this.lastName = lastName; this.sex = sex; } public User() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } @Override public String toString() { return "User [id=" + id + ", lastName=" + lastName + ", sex=" + sex + "]"; } }
UserMapper.java
package com.Mapper; import java.util.List; import com.pojo.User; //不需要写UserMapper的实现类 public interface UserMapper { public int saveUser(User user); public int deleteById(Integer id); public int updateUser(User user); public User queryUserById(Integer id); public List<User> queryUsers(); }
UserMapper.xml
<?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.Mapper.UserMapper"> <!-- public int saveUser(User user); --> <insert id="saveUser" parameterType="com.pojo.User"> insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex}) </insert> <!-- public int deleteById(Integer id); --> <delete id="deleteById"> delete from t_user where id = #{id} </delete> <!-- public int updateUser(User user); --> <update id="updateUser" parameterType="com.pojo.User"> update t_user set last_name=#{lastName},sex=#{sex} where id = #{id} </update> <!-- public User queryUserById(Integer id); --> <select id="queryUserById" resultType="com.pojo.User"> select id,last_name lastName,sex from t_user where id=#{id} </select> <!-- public List queryUsers(); --> <select id="queryUsers" resultType='com.pojo.User'> select id,last_name lastName,sex from t_user </select> </mapper>