mybatis的通用mapper的通用Example使用,当然也有不对应通用mapper的普通Example使用
想要偷懒不写mybatis里的一大堆mapper.xml文件,就想使用通用的Mapper类减少工作量。
首先,我使用的是Maven项目,所以导入Mapper的Maven依赖
- <dependency>
- <groupId>tk.mybatis</groupId>
- <artifactId>mapper</artifactId>
- <version>3.2.0</version>
- </dependency>
同时有一项必要依赖项:项目依赖于JPA的注解,需要添加Maven依赖:
- <dependency>
- <groupId>javax.persistence</groupId>
- <artifactId>persistence-api</artifactId>
- <version>1.0</version>
- </dependency>
接下来,在配置文件applicationContext.xml中配置Mapper
- <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.isscas.ucqcs.common.dao"/>
- <property name="properties">
- <value>
- mappers=tk.mybatis.mapper.common.Mapper //这是Mapper接口配置,当接口为此默认配置时,可不写
- </value>
- </property>
- </bean>
直接将MyBatis的配置 org 修改为 tk 即可
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
到这里,Mapper的配置已经全部完成。
只要在自己的Mapper接口上继承Mapper<T>接口,即可调用通用Mapper类中全部的方法。
另外要注意的是:该Mapper类对实体类有自己的解析方式 : 表名和字段名会默认使用类名,驼峰转下划线(即UserNamed对应表名/字段名user_name),使用@Column(name = "真实名称")可以指定表名/字段名。
另,需要@Id标记主键字段,对不需要的字段,可用@Tranisent忽略
Mapper接口中包含单表的增删改查分页功能。
下面给出一个查询实例:
- CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
- //查询全部
- List<Country> countryList = mapper.select(new Country());
- //总数
- //通用Example查询
- Example example = new Example(Country.class);
- example.createCriteria().andGreaterThan("id", 100);//这里给出的条件查询为id>100
- countryList = mapper.selectByExample(example);
项目示例:
@Override
public String getSimpleOfTree(String customerKey) {
// TODO Auto-generated method stub
Example example = new Example(TbCusFirmrelgroup.class);///注意用的是类中的属性,不是数据库中的属性
example.setOrderByClause("groupKey asc");//注意用的是类中的属性,不是数据库中的属性
example.createCriteria().andEqualTo("customerKey",BigDecimal.valueOf(Long.valueOf(customerKey)));
List<TbCusFirmrelgroup> cusPowerGroupList = tbCusFirmrelgroupMapper.selectByExample(example);
return null;
}