您的位置:首页 > 其它

Mybatis的入门的注意事项

2015-01-17 20:52 253 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: