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) {
}
}
}
}
}