mybatis逆向工程

新建一个JAVA工程
在工程目录下建一个lib文件夹目录
拷贝需要的jar包到lib文件下.并builtpath

log4j-1.2.16.jar
mybatis-3.2.7.jar
mybatis-generator-core-1.3.2.jar
mysql-connector-java-5.1.7-bin.jar

添加log4j依赖的文件log4j.properties在scr目录下;

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

在工程目录下创建gerneralConfig.xml文件





    
        
            
            
        
        
        
        
        

        
        
            
        

        
        
            
            
            
            
        
        
        
            
            
        
        
        
            
            
        
        

        

创建一个类,并添加如下方法。引入mybatis文件


public void generator() throws Exception{
        List warnings = new ArrayList();
        boolean overwrite = true;
        File configFile = new File("genarator.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);
    }
    
    public static void main(String[] args) throws Exception {
        try {
            StartServer startServer = new StartServer();
            startServer.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

编译,运行。

配置文件需要注意的地方有:
连接数据库的名称,密码;
指定数据库表;
**
映射文件路径;
Mac OS 的路径写法:./src;
Windows的路径写法:.\src;
**

拷贝出来生成的文件到自己的项目中;
在SqlMapConfig.xml中添加映射

 
        
    
    
  

在测试方法中添加:


private SqlSession openSession;

    // 注解Before  :每次方法执行前都会执行这里
    @Before  
    public void init() throws IOException {

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
        openSession = build.openSession();
    }


    @Test
    public void testGetuserName() {
        
        DeptMapper mapper1 = openSession.getMapper(DeptMapper.class);
        
        Dept dxDept = new Dept();
        dxDept.setDeptno(50);
        dxDept.setDname("abc");
        dxDept.setLoc("china");

        openSession.commit();
        openSession.close();
         int insert = mapper1.insert(dxDept);
        System.out.println(insert);
    }

你可能感兴趣的:(mybatis逆向工程)