2014-01-14 85 views
3

我想從表中使用jooq以編程方式而不是.xml創建.java。如何使用jooq而不是xml從表中創建java pojo?

我已經嘗試了xml,但它不是我想要的。

首先有可能通過jooq來完成嗎?

其次有人知道該怎麼做嗎?

import org.jooq.DSLContext; 
import org.jooq.Record; 
import org.jooq.Result; 
import org.jooq.SQLDialect; 
import org.jooq.impl.DSL; 
import org.jooq.util.DefaultGenerator; 
import org.jooq.util.JavaGenerator; 
import org.jooq.util.mysql.MySQLDatabase; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
public class Main { 
    public static void main(String[] args) { 
     Connection conn = null; 

     String userName = "root"; 
     String password = "root"; 
     String url = "jdbc:mysql://localhost:3306/library"; 

     try { 
      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
      conn = DriverManager.getConnection(url, userName, password); 

      DSLContext create = DSL.using(conn, SQLDialect.MYSQL); 
      Result<Record> result = create.select().from("AUTHOR").fetch(); 

      //------------ here I want to create AUTHOR.java from table AUTHOR by connecting to database 
      DefaultGenerator g = new DefaultGenerator(); 
      MySQLDatabase database = new MySQLDatabase(); 
      database.getSchema(conn.getSchema()); 
      JavaGenerator javaGenerator = new JavaGenerator(); 
      javaGenerator.generate(database); 

      //------------ 

      for (Record r : result) { 
       Long id = r.getValue(AUTHOR.ID); 
       String firstName = r.getValue(AUTHOR.FIRST_NAME); 
       String lastName = r.getValue(AUTHOR.LAST_NAME); 

       System.out.println("ID: " + id + " first name: " + firstName + " last name: " + lastName); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (conn != null) { 
       try { 
        conn.close(); 
       } catch (SQLException ignore) { 
       } 
      } 
     } 
    } 
} 

回答

3

是的,你可以編程配置jOOQ的代碼生成器。當你看GenerationTool的源代碼,你會看到,你可以調用它的重載main()方法無論是從控制檯(as documented in the manual),或者通過傳遞一個org.jooq.util.jaxb.Configuration對象。一個例子:

import org.jooq.util.jaxb.*; 

// [...] 

Configuration configuration = new Configuration() 
    .withJdbc(new Jdbc() 
     .withDriver("com.mysql.jdbc.Driver") 
     .withUrl("jdbc:mysql://localhost:3306/library") 
     .withUser("root") 
     .withPassword("root")) 
    .withGenerator(new Generator() 
     .withName("org.jooq.util.DefaultGenerator") 
     .withDatabase(new Database() 
      .withName("org.jooq.util.mysql.MySQLDatabase") 
      .withIncludes(".*") 
      .withExcludes("") 
      .withInputSchema("library")) 
     .withTarget(new Target() 
      .withPackageName("org.jooq.util.maven.example") 
      .withDirectory("target/generated-sources/jooq"))); 

GenerationTool.main(configuration); 

以上配置的POJO由XJC生成的,因此可以使用完全相同的結構,與XML配置。

This is now also documented in the manual