Mybatis的入门的注意事项

Mybatis的参考文档:http://mybatis.github.io/mybatis-3/zh/index.html


mybatis使用的注意事项:

1.在Mybatis的配置文件mybatis-config.xml中,一定不要忘记添加一些mapper.xml文件;

  <mappers>
    <mapper resource="com/milks/model/User.xml"/>
  </mappers>

2.得到SqlSession后,一定注意调用的参数正确,“哪个mapper配置文件中的哪个方法”;

session.selectOne("com.milks.model.User.select", 1);//如果配置文件中采用alias,那么User也不需要加上命名空间;


3.在mapper的配置文件中,一定注意类的命名空间;(在select方法中,也需要加上命名空间)

<mapper namespace="com.milks.model.User">
  <select id="select" resultType="com.milks.model.User" parameterType="int">
    select * from t_user where id = #{id}
  </select>
</mapper>


4.  Mybatis的配置文件typeAliases的使用;

<configuration>
	<properties resource="jdbc.properties"/>
	<typeAliases>
		<package name="itat.zttc.shop.model"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<!-- 将mapper文件加入到配置文件中 -->
	<mappers>
		<mapper class="itat.zttc.shop.mapper.UserMapper"/>
	</mappers>
</configuration>

在配置文件中加上这个标签就可以使用alias了,也就是类的简写了

5.mapper的使用

首先穿件一个UserMapper 接口;

package itat.zttc.shop.mapper;

import itat.zttc.shop.model.User;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
	/**
	 * 基于Annation的方法仅仅知道就ok
	 * @param user
	 */
	@Insert("insert into t_user (username,password,nickname,type) value (#{username},#{password},#{nickname},#{type})")
	public void add(User user);
	public void update(User user);
	public void delete(int id);
	
	@Select("select * from t_user where id=#{id}")
	public User load(int id);
	@Select("select * from t_user")
	public List<User> list();
}


注意:一定要把配置文件的命名空间改变。。

before:

<mapper namespace="com.milks.model.User">
After:
<mapper namespace="com.milks.model.UserMapper<span style="font-family: Arial, Helvetica, sans-serif;"> </span>">


使用方式:

User user = session.getMapper(UserMapper.class).select(1);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值