使用MybatisGenerator

1、向pom.xml添加依赖项


            mysql
            mysql-connector-java
            8.0.22



            org.mybatis.generator
            mybatis-generator-core
            1.3.7

Mybais-Generator依赖JDBC

2、编写config文件





    
    

    
    
        
        

        
        
            
            
        

        
        
            
        

        
        
            
        

        
        

3、运行命令行生成(也可以通过4、java程序生成)

java -jar PACKAGE_NAME -configfile CONFIG_FILE_NAME

其中,PACKAGE_NAME替换为maven仓库下载的mybatis-generator-core-1.4.0.jar的绝对路径,CONFIG_FILE_NAME替换为你写的配置文件的绝对路径
(如果有必要)

4、使用Java程序生成

public class Main {

    static public void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List warnings = new ArrayList();
        boolean overwrite = true;
        File configFile = new File("src/main/java/com/william/mapper/generator.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);


    }
}

将其中file路径替换即可,否则会报错

 

5、使用产生的Example

static public void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        System.out.println(inputStream.toString());
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);

        StudentExample studentExample = new StudentExample();
        studentExample.createCriteria().andAgeBetween(18,100);
        List students = mapper.selectByExample(studentExample);
        students.stream().forEach(student -> log.info(students.toString()));

    }

能够使用Example产生Criteria,能够用代码拼接sql语句。

优点:开发较快

缺点:效率低下,可能写出低效的sql

你可能感兴趣的:(java,Mybatis)