mybatis学习之路mapper代理开发方法-开发规范及实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis学习之路mapper代理开发方法-开发规范及实现相关的知识,希望对你有一定的参考价值。

 

1.在mapper.xml中namespace等于mapper接口得地址

<?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.jjt.ssm.mapper.TuserMapper">

  <select id="findUserById" parameterType="int" resultType="com.jjt.ssm.pojo.Tuser">

    SELECT * FROM tuser WHERE id=#{userid}

  </select>

</mapper>

2.mapper.java接口中的方法名字和mapper.xml中的statement即(findUserById)一致

3.mapper.java接口中的方法输入参数类型和mapper.xml和statement的parameterType指定类型保持一致。

4.mapper.java接口中的返回类型和mapper.xml和statement的resultType指定类型保持一致。

import com.jjt.ssm.pojo.Tuser;

public interface TuserMapper {
  public Tuser findUserById(int userid) throws Exception;
}

 

sqlMapConfig.xml配置

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 和spring整合后这个 environments 移除-->

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC" />
    <!-- 配置数据库连接信息 -->
    <dataSource type="POOLED">
    <!-- value属性值引用db.properties配置文件中配置的值 -->
      <property name="driver" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://127.0.0.1:3306/jiajitao?useUnicode=true&amp;characterEncoding=UTF-8" />
      <property name="username" value="root" />
      <property name="password" value="root" />
    </dataSource>
  </environment>
</environments>

  <mappers>
    <!-- <mapper resource="sqlmap/Tuser.xml"/> -->
    <mapper resource="mapper/TuserMapper.xml"/>
  </mappers>
</configuration>

 

测试类

 

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.jjt.ssm.pojo.Tuser;

public class TuserMapperTest {
SqlSessionFactory sqlSessionFactory;

@Before
public void setUp() throws Exception {
  String resource = "sqlMapConfig.xml";
  // 配置文件读取
  InputStream inputStream = Resources.getResourceAsStream(resource);

  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

@Test
public void testFindUserById() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  TuserMapper userMapper = sqlSession.getMapper(TuserMapper.class);
  Tuser user = userMapper.findUserById(1);
  System.out.println(user.getUsername());

}

}










































以上是关于mybatis学习之路mapper代理开发方法-开发规范及实现的主要内容,如果未能解决你的问题,请参考以下文章

Spring+SpringMVC+MyBatis深入学习及搭建——MyBatis原始Dao开发和mapper代理开发

Spring+SpringMVC+MyBatis深入学习及搭建——MyBatis原始Dao开发和mapper代理开发(转发同上)

Mybatis学习总结二

Mybatis学习第二天——mapper的动态代理

Mybatis学习系列Mapper接口动态代理

MyBatis - Mapper动态代理开发