mybatis开发DAO的2种方法

第一种

原始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的错误



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值