147_Java_SpringMybatis_Mybatis_Generator

网友投稿 524 2022-05-30

MyBatis-逆向工程

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,

可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。

但是表连接、存储过程等这些复杂sql的定义需要我们手工编写

147_Java_SpringMybatis_Mybatis_Generator

• 官方文档地址

http://www.mybatis.org/generator/

• 官方工程地址

https://github.com/mybatis/generator/releases

MBG使用步骤:

1 编写MBG的配置文件(重要几处配置)

1)jdbcConnection配置数据库连接信息

2)javaModelGenerator配置javaBean的生成策略

3)sqlMapGenerator 配置sql映射文件生成策略

4)javaClientGenerator配置Mapper接口的生成策略

5)table 配置要逆向解析的数据表 tableName:表名 domainObjectName:对应的javaBean名

2 运行代码生成器生成代码

public class MyBatisTest { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testMbg() throws Exception { List warnings = new ArrayList(); boolean overwrite = true; File configFile = new File("mbg.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } @Test public void testMyBatis3Simple() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try{ EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); List list = mapper.selectByExample(null); for (Employee employee : list) { System.out.println(employee.getId()); } }finally{ openSession.close(); } } @Test public void testMyBatis3() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try{ EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); //xxxExample就是封装查询条件的 //1、查询所有 //List emps = mapper.selectByExample(null); //2、查询员工名字中有e字母的,和员工性别是1的 //封装员工查询条件的example EmployeeExample example = new EmployeeExample(); //创建一个Criteria,这个Criteria就是拼装查询条件 //select id, last_name, email, gender, d_id from tbl_employee //WHERE ( last_name like ? and gender = ? ) or email like "%e%" Criteria criteria = example.createCriteria(); criteria.andLastNameLike("%e%"); criteria.andGenderEqualTo("1"); Criteria criteria2 = example.createCriteria(); criteria2.andEmailLike("%e%"); example.or(criteria2); List list = mapper.selectByExample(example); for (Employee employee : list) { System.out.println(employee.getId()); } }finally{ openSession.close(); } } }

Generator Java MyBatis

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:文字折叠效果 CSS
下一篇:JQuery必备基础知识(一)
相关文章