发布于 2015-05-15 01:53:40 | 407 次阅读 | 评论: 0 | 来源: 网友投递
MyBatis 基于Java的持久层框架
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
通用Mapper可以极大的方便开发人员。
为了让您更方便的了解通用Mapper,下面贴一段代码来看实际效果。
通用Mapper可以缓存,全部针对单表操作,每个实体类都需要继承通用Mapper接口来获得通用方法。
示例代码:
CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); //查询全部 List<Country> countryList = mapper.select(new Country()); //总数 Assert.assertEquals(183, countryList.size()); //通用Example查询 Example example = new Example(Country.class); example.createCriteria().andGreaterThan("id", 100); countryList = mapper.selectByExample(example); Assert.assertEquals(83, countryList.size()); //MyBatis-Generator生成的Example查询 CountryExample example2 = new CountryExample(); example2.createCriteria().andIdGreaterThan(100); countryList = mapper.selectByExample(example2); Assert.assertEquals(83, countryList.size());
CountryMapper代码如下:
public interface CountryMapper extends Mapper<Country> { }
这里不说更具体的内容,如果您有兴趣,可以查看下面的项目文档
从上面效果来看也能感觉出这是一种类似hibernate的用法,因此也需要实体和表对应起来,因此使用了JPA注解。更详细的内容可以看下面的项目文档。
Country代码:
public class Country { @Id private Integer id; @Column private String countryname; private String countrycode; //省略setter和getter方法 }
使用Mapper专用的MyBatis Generator插件 可以方便的生成这些(带注解的)实体类。
解决Example查询中的and缺少空格的问题
去掉UUID和JDBC两种主键策略类型中对字段类型的限制 不再限制为String,可以是任意简单类型,需要自己保证类型匹配。例如UUID配置的策略可以返回Integer,那么字段类型必须是Integer。
JDBC类型的主键策略可以配置多个,就相当于keyProperties="id1,id2..."
EntityHelper的getOrderByClause方法返回值从StringBuilder改为String,解决@OrderBy注解时的异常
提前预告:下个版本3.0.0会将通用Mapper项目拆分为两个项目,会有一些大的改动
如果你使用Maven,只需要添加如下依赖:
<dependency> <groupId>com.github.abel533</groupId> <artifactId>mapper</artifactId> <version>2.3.3</version> </dependency>
如果你想引入Jar包,你可以从下面的地址下载:
https://oss.sonatype.org/content/repositories/releases/com/github/abel533/mapper/
http://repo1.maven.org/maven2/com/github/abel533/mapper/
由于通用Mapper依赖JPA,所以还需要下载persistence-api-1.0.jar:
http://repo1.maven.org/maven2/javax/persistence/persistence-api/1.0/
作者博客:http://blog.csdn.net/isea533
作者邮箱: abel533@gmail.com
Mybatis工具群: 211286137 (Mybatis相关工具插件等等)
推荐使用Mybatis分页插件:PageHelper分页插件
官方网站:www.mybatis.tk
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。