MyBatis逆向工程
使用官方网站的Mapper自动生成工具mybatis-generator-core-1.3.2来生成pojo类和Mapper映射文件
1.导入逆向工程如下图方式进行导入:
在generatorConfig.xml中配置Mapper生成的详细信息,如下图:
注意修改以下几点:
- 修改要生成的数据库表
- pojo文件所在包路径
- Mapper所在的包路径
配置文件如下:
4.生成逆向工程代码
找到下图所示的java文件,执行工程main主函数,
刷新工程,发现代码生成,如下图:
-
复制生成的代码到mybatis-spring工程,如下图
-
修改spring配置文件 在applicationContext.xml修改
- 编写测试方法:
public class UserMapperTest {
private ApplicationContext context;
@Before
public void setUp() throws Exception {
this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void testInsert() {
// 获取Mapper
UserMapper userMapper = this.context.getBean(UserMapper.class);
User user = new User();
user.setUsername("曹操");
user.setSex("1");
user.setBirthday(new Date());
user.setAddress("三国");
userMapper.insert(user);
}
@Test
public void testSelectByExample() {
// 获取Mapper
UserMapper userMapper = this.context.getBean(UserMapper.class);
// 创建User对象扩展类,用户设置查询条件
UserExample example = new UserExample();
example.createCriteria().andUsernameLike("%张%");
// 查询数据
List list = userMapper.selectByExample(example);
System.out.println(list.size());
}
@Test
public void testSelectByPrimaryKey() {
// 获取Mapper
UserMapper userMapper = this.context.getBean(UserMapper.class);
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user);
}
}
注意
- 逆向工程生成的代码只能做单表查询
- 不能在生成的代码上进行扩展,因为如果数据库变更,需要重新使用逆向工程生成代码,原来编写的代码就被覆盖了。
- 一张表会生成4个文件