首先不管如何记得在配置文件里写入映射文件(<mapper>标签)
实体类参考
public class Person {
private Integer pId;
private String pName;//当和表里的列名不一致的时候,查询语句应该起别名
//p_Name(原表里的列名) pname别名
private String email;
public Person() {
}
接口
package com.yiki.Dao;
import com.yiki.Entity.Person;
import org.apache.ibatis.annotations.Param;
public interface PersonMapperPlus {
public Person getPersonById(Integer id);
}
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.yiki.Dao.PersonMapperPlus">
<!--对某个bean自定义映射规则
【type】写全类名和别名都可以(前提是写了别名)
【id】这个规则的唯一标识-->
<resultMap id="myRule" type="com.yiki.Entity.Person">
<!--指定主键列,使得框架优化规则
【column】指定列
【property】制定对应bean的属性值-->
<id column="pId" property="pId"/>
<!--指定普通列-->
<result column="pName" property="p_Name"/>
<result column="email" property="email"/>
<!--其他列名不指定也可以自动封装,但是还是最好都写上-->
</resultMap>
<!--【resultMap】自定义结果集映射规则(不能和resultType混用-->
<select id="getPersonById" resultMap="myRule">
select * from Person where pid=#{pId}
</select>
</mapper>
测试类
package com.yiki.Test;
import com.yiki.Dao.PersonMapper;
import com.yiki.Dao.PersonMapperAnno;
import com.yiki.Dao.PersonMapperPlus;
import com.yiki.Entity.Person;
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.apache.log4j.Logger;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class TestPlus {
private String resource;
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private PersonMapperPlus mapper;
private Logger log;
public void start() throws IOException {
resource = "mybatis.xml";//根据全局配置文件
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(PersonMapperPlus.class);
log = Logger.getLogger(this.getClass());
}
@Test
public void test1() throws IOException {
start();
Person person = mapper.getPersonById(1);
System.out.println(person);
sqlSession.close();
}
}