Mybatis中配置Mapper的方法
在这篇文章中我主要想讲一下Mybatis配置文件中mappers元素的配置。关于基础部分的内容可以参考http://blog.csdn.net/elim168/article/details/40622491。
我们知道在Mybatis中定义Mapper信息有两种方式,一种是利用xml写一个对应的包含Mapper信息的配置文件;另一种就是定义一个Mapper接口,然后定义一些相应的操作方法,再辅以相应的操作注解。
现假设我有这样一个实体类:
- package com.tiantian.mybatis.model;
- public class User {
- private int id;
- private String name;
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
它对应的数据库表结构是这样的:
然后我要利用Mybatis对它做一个简单的增删改查操作,那么如果利用xml配置Mapper的方式来定义的话,我对应的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.tiantian.mybatis.mapper.UserMapper">
- <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id">
- insert into t_user(name, age) values(#{name}, #{age})
- </insert>
- <update id="updateUser" parameterType="User">
- update t_user set name=#{name}, age=#{age} where id=#{id}
- </update>
- <select id="findById" parameterType="int" resultType="User">
- select * from t_user where id=#{id}
- </select>
- <delete id="deleteUser" parameterType="int">
- delete from t_user where id=#{id}
- </delete>
- </mapper>
如果使用接口加注解的方式,那么我们的UserMapper接口应该这样定义:
- package com.tiantian.mybatis.mapperinterface;
- import org.apache.ibatis.annotations.Delete;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Select;
- import org.apache.ibatis.annotations.Update;
- import com.tiantian.mybatis.model.User;
- public interface UserMapper {
- @Insert("insert into t_user(name, age) values(#{name}, #{age})")
- public void insertUser(User user);
- @Update("update t_user set name=#{name}, age=#{age} where id=#{id}")
- public void updateUser(User user);
- @Select(