General Example use of mybatis general mapper , of course, there are also general Example uses that do not correspond to general mapper
If you want to be lazy and not write a lot of mapper.xml files in mybatis, you want to use the generic Mapper class to reduce the workload.
First, I'm using a Maven project, so import Mapper's Maven dependencies
- <dependency>
- <groupId>tk.mybatis</groupId>
- <artifactId>mapper</artifactId>
- <version>3.2.0</version>
- </dependency>
At the same time, there is a necessary dependency: the project depends on JPA annotations, and Maven dependencies need to be added:
- <dependency>
- <groupId>javax.persistence</groupId>
- <artifactId>persistence-api</artifactId>
- <version>1.0</version>
- </dependency>
Next, configure Mapper in the configuration file applicationContext.xml
- <beanclass="tk.mybatis.spring.mapper.MapperScannerConfigurer">
- <propertyname="basePackage"value="com.isscas.ucqcs.common.dao"/>
- <propertyname="properties">
- <value>
- mappers = tk .mybatis.mapper.common.Mapper //This is the Mapper interface configuration. When the interface is configured by default, it is not necessary to write
- </value>
- </property>
- </bean>
Just change the configuration org of MyBatis to tk directly
- <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
At this point, the configuration of Mapper has been completed.
As long as you inherit the Mapper<T> interface on your own Mapper interface, you can call all the methods in the general Mapper class.
另外要注意的是:该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);///Note that the attributes in the class are used, not the attributes in the database
example.setOrderByClause(" groupKey asc");// Note that the properties in the class are used, not the properties in the database
example.createCriteria().andEqualTo("customerKey",BigDecimal.valueOf(Long.valueOf(customerKey)));
List<TbCusFirmrelgroup> cusPowerGroupList = tbCusFirmrelgroupMapper.selectByExample(example);
return null;
}