1、mybatis逆向工程
如果使用mybatis觉得写sql映射文件和mapper接口甚至实体类麻烦时,这时可以使用mybatis逆向工程来帮我们生成这些,我们需要做的只是
1. 修改要生成的数据库表
2. 实体类文件所在包路径
3. Mapper接口文件所在的包路径
接着mybatis整合spring
搭建好的环境来做。
1、引入逆向工程generatorSqlMapCustom
如果下载的逆向工程有多个xml文件,除了上面那个generatorConfig.xml其他都可以删了。
2、修改xml文件generatorConfig.xml
1). 修改要生成的数据库表
2). 实体类文件所在包路径
3). Mapper接口文件所在的包路径
比如我的修改如下:
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis2" userId="root"
password="123456">
</jdbcConnection>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.scu.mybatis.mapper"
targetProject=".\src">
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.scu.mybatis.mapper"
targetProject=".\src">
<!-- 指定数据库表 -->
<table schema="" tableName="t_user"></table>
<table schema="" tableName="t_order"></table>
执行GeneratorSqlmap的main方法
刷新项目再查看
将生成的文件都拷贝到,mybatis与spring整合好的工程中。
测试:
//查询id为1的用户
@Test
public void test2(){
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TUserMapper mapper = ac.getBean(TUserMapper.class);
TUserExample example = new TUserExample();
Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(1);
List<TUser> list = mapper.selectByExample(example);
for (TUser tUser : list) {
System.out.println(tUser.getUsername()+","+tUser.getAddress());
}
}
数据库t_user表中现有32条数据
输出:
小红,安徽合肥
2、mybatis分页插件pagehelper
1、下载分页插件pagehelper
我这里下了个工程下来,将里面的5个文件拷贝到上面的工程中。
2、工程中导入jar包
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9</version>
</dependency>
3、mybatis全局配置文件SqlMapConfig.xml中引入该插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
4、测试:
需求:根据用户名查询用户信息,要求分页查询,查询第二页每页显示10条数据,要求查询结果按照id降序排列。
@Test
public void test3(){
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
PageHelper.startPage(2, 10);
TUserMapper mapper = ac.getBean(TUserMapper.class);
TUserExample example = new TUserExample();
Criteria criteria = example.createCriteria();
//根据用户名模糊查询
criteria.andUsernameLike("%小%");
//id升序排
example.setOrderByClause("id desc");
List<TUser> list = mapper.selectByExample(example);
PageInfo<TUser> info = new PageInfo<>(list);
list = info.getList();
System.out.println("总记录数:"+info.getTotal());
System.out.println("总页数:"+info.getPages());
System.out.println("每页显示条数:"+info.getPageSize());
for (TUser tUser : list) {
System.out.println(tUser.getId()+","+tUser.getUsername()+","+tUser.getAddress());
}
}
输出:
总记录数:32
总页数:4
每页显示条数:10
24,小19,安徽19市
23,小18,安徽18市
22,小17,安徽17市
21,小16,安徽16市
20,小15,安徽15市
19,小14,安徽14市
18,小13,安徽13市
17,小12,安徽12市
16,小11,安徽11市
15,小10,安徽10市
注:如果在阿里云库下了那个pagehelper-5.1,将坐标添加到了pom.xml中,那么测试会出现PageHelper类转换为拦截器(PageHelper实现了拦截器接口)异常,网上有人说是mybatis包的版本低了要3.3以上,如果换成了3.3以上还不行就建议使用上面介绍的那种方式,拷一下文件引入一下jsqlparser这个jar包。