(四)mybatis逆向工程
阅读原文时间:2023年07月16日阅读:1

构建

逆向工程就是说通过数据库当中的表生成class,mapper,接口,不需要自己编写那些,很方便。跟symfony里面的自动生成是一样的;视频里的人说用的不多,但我觉得很方便呀

具体步骤,首先导入MyBatis-generator-core.jar,

之后复制一下generator.xml文件:里面有注释,很容易看懂














    <javaClientGenerator type="XMLMAPPER" targetPackage="Mapper" targetProject="src">  
        <property name="enableSubPackages" value="true"/>  
    </javaClientGenerator>  
    <table tableName="Student"></table>  
    <table tableName="Adress"></table>  
    <!--生成对应表及类名-->  




将路径名,表明等更改正确,

main函数之中,复制以下代码,运行就Ok,

    File file = new File("src/generator.xml");

    List<String> warnings = new ArrayList<String>();  
    ConfigurationParser cp = new ConfigurationParser(warnings);  
    Configuration config = cp.parseConfiguration(file);  
    DefaultShellCallback callback = new DefaultShellCallback(true);  
    MyBatisGenerator generator = new MyBatisGenerator(config,callback,warnings);  
    generator.generate(null);

如何使用:

生成之后可以看到有两种class,一种是student,另一种是studentExample,我们具体使用时候就是通过example来使用的;

Reader reader = Resources.getResourceAsReader("config.xml");
//connection
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();

    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);  / /studentMapper 

    StudentExample studentExample = new StudentExample();            // 构建查询条件  
    StudentExample.Criteria criteria = studentExample.createCriteria();  
    criteria.andIdBetween(,);   // id在1,2之间  
    criteria.andNameLike("%飞%");  //模糊查询名字  

    
    // 调用mapper方法进行查询
List students = studentMapper.selectByExample(studentExample); / / 传入查询条件类进行查询
for (Student temp:students
) {System.out.println(temp);
}

这里是通过初始化一个studentExample类,之后对它的criteria添加一些条件,再将studentExample传入查询mapper的某一个方法中就行了。

当然我们也可以有两个criteria,相当于sql语句查询条件是 or  的关系

如下示例,我们再创建一个criteria

StudentExample.Criteria criteria2 = studentExample.createCriteria();
criteria2.andNameLike("%三%");

查询时默认使用第一个criteria,如果要拼接为或关系的话,使用:

studentExample.or(criteria2);

这样子,查询时构建的sql语句条件就是用or连接两个criteria

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章