您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
14-注解开发(简单sql用注解更便捷)
发布时间:2024-11-22 20:10:35编辑:雪饮阅读()
-
前番学习了mapper配置文件中进行的各种sql编写,那么其实如果对于一些简单的sql来说,则是没有必要非写到mapper配置文件中,直接在mapper映射的抽象类中的抽象方法中使用注解即可。
如
@Select("select * from tb_brand where id > #{id}")
List<Brand> selectByIdByAnnotation(int id);
然后调用该抽象方法的实现则如
@Test
public void testAnnotation() throws IOException {
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession(true);
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
List<Brand> brands=brandMapper.selectAll();
//求取最小id
int id=-1;
if(brands.size()>0){
for(int i=0;i<brands.size();i++){
int tid=brands.get(i).getId();
if(id!=-1){
if(tid<id){
id=tid;
}
continue;
}
id=tid;
}
}
System.out.println("id:"+id);
if(id!=-1){
brands=brandMapper.selectByIdByAnnotation(id);
System.out.println(brands);
}
sqlSession.close();
}
关键字词:注解,sql
上一篇:13-参数传递arg,param,List,Array,Map(mapper接口的param注解与map的原理)
下一篇:04-HTTP-响应数据格式(java7的try-with-resources及实现一个简单的java版http服务器)