public class User {
private int id;
private String name;
private int age;
//getter、setter...
}
2.接口类UserMapper.java
public interface UserMapper {
//添加
public int addUser(User user) throws Exception;
//删除
public void deleteUser(int id) throws Exception;
//修改
public void updateUser(User user) throws Exception;
//查询
public User queryUser(int id) throws Exception;
//查询所有的用户
public List<User> queryAllUser() throws Exception;
}
3.映射文件userMapper.xml
<mapper namespace="com.test.xmlAndAnno.UserMapper">
<!-- 自定义结果集 -->
<resultMap type="com.test.bean.User" id="userMap">
<id property="id" column="id" javaType="java.lang.Integer"/>
<result property="name" column="name" javaType="java.lang.String"/>
<result property="age" column="age" javaType="java.lang.Integer"/>
</resultMap>
<!-- 增删改查标签的id属性必须和接口中的方法名相同,
id属性值必须是唯一的,不能够重复使用,
parameterType属性表示形参参数类型,
resultType属性表示查询时返回的结果集类型
-->
<!-- userGeneratedKeys(仅对insert有用),会告诉Mybatis使用JDBC的getGeneratedKeys方法来取出由MySQL内部生成的主键,默认值false。
keyProperty(仅对insert有用)标记一个属性,mybatis会通过getGeneratedKey或者通过insert语句的selectKey子元素设置值,默认不设置。
-->
<insert id="addUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.test.bean.User">
insert into users (name,age) values (#{name},#{age})
</insert>
<delete id="deleteUser" parameterType="int">
delete from users where id = #{id}
</delete>
<update id="updateUser" parameterType="com.test.bean.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
<select id="queryUser" parameterType="int" resultType="com.test.bean.User" >
select * from users where id = #{id}
</select>
<select id="queryAllUser" resultMap="userMap">
select * from users
</select>
</mapper>