上接:mybatis注解开发-@Results和@Result注解
介绍
在 mybatis注解开发-@Results和@Result注解 中,通过 @Results 注解定义 实体类 与 表 映射
在 Mapper接口 的其他方法中,如果也想用该 @Results,可以通过 @ResultMap 注解指定
注意: @Results 和 @ResultMap 不能同时修饰同一个方法
源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ResultMap {
String[] value();
}
可以看到 value 是数组
例子
修改IUserMapper
增加 一个查询,并且 通过 @ResultMap指定 之前定义过的 @Results
package top.malaoshi.mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.type.JdbcType;
import top.malaoshi.entity.User;
import java.util.Date;
import java.util.List;
public interface IUserMapper {
@Select("select id,username,password,age,sex,status,create_time from user")
@Results(id="UserMap",value={
@Result(property = "id",column = "id",id=true),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "age",column = "age"),
@Result(property = "sex",column = "sex"),
@Result(property = "status",column = "status"),
@Result(property = "createTime",column = "create_time")
})
public List<User> query();
@Select("select id,username,password,age,sex,status,create_time from user where id=#{id}")
@ResultMap(value={"UserMap"}) //完全写法,使用上面已经定义好的UserMap
//@ResultMap("UserMap") //简化写法
public User queryById(String id);
}
由于只传入 一个基本数据类型,所以在sql中 #{id}可以写成任意值,如:#{aaa}也是可以的,但代码规范不允许这么写
测试
@org.junit.Test
public void test3() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
User u=mapper.queryById("10001");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm");
String createTime=sdf.format(u.getCreateTime());
String info = String.format("id:%s,用户名:%s,创建时间:%s", u.getId(), u.getUsername(),createTime);
System.out.println(info);
sqlSession.close();
inputStream.close();
}