第一种
原始dao开发,程序猿要写dao接口和dao实现类。
第二种
mapper代理,程序猿只要写mapper接口,但是需要注意以下4个开发规范。
1,在mapper.xml中的nameSpace(命名空间),要和mapper接口的地址相同
<mapper namespace="com.coci.mapperDao.IUserDAo">
2,mapper.java接口中的方法名和mapper.xml中的statement的id一致
mapper.xml中这样写:
<select id="findById" parameterType="int" resultType="com.coci.entity.User">
select * from user where uid=#{id11}
</select>
mapper.java接口中这样写:
public User findById(int uid) throws Exception;
3,mapper.java接口中的方法输入参数类型和mapper.xml中statament的parameterType指定类型一致
4,mapper.java接口中的返回值类ixnghemapper.xml中的statement的ResultType指定类型一致
例子:
接口中代码:
public interface IUserDAo {
/**
* 查询单个用户,根据id
* @param uid
* @return
* @throws Exception
*/
public User findById(int uid) throws Exception;
public List<User> findUserByName(String uname) throws Exception;
public void addUser(User user) throws Exception;
}
mapper.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.coci.mapperDao.IUserDAo">
<!-- #:如果是简单数据类型,里面的参数名可以随便写 -->
<select id="findById" parameterType="int" resultType="com.coci.entity.User">
select * from user where uid=#{id11}
</select>
<!-- $ :里面的参数名称只能使用value -->
<select id="findUserByName" parameterType="string" resultType="com.coci.entity.User">
select * from `user` where uname LIKE '%${value}%'
</select>
<insert id="addUser" parameterType="com.coci.entity.User">
<!-- 返回刚刚插入数据的id -->
<selectKey order="AFTER" keyProperty="uid" resultType="int">
select LAST_INSERT_ID()
</selectKey>
insert into user(uname,uage) values(#{uname},#{uage})
</insert>
</mapper>
注意:
别忘记在sqlMapperConfig.xml中挂载配置的映射文件,否则会报not found的错误