好久没上来了,最近玩了玩java,学习了一下JOOQ,轻量级的ORM,用起来比hibernet灵活很多,大部分代码由工具生成。下面是一个例子。希望地初学者有帮助。
开发环境eclipse。
对于任何一个ORM工具,我们都必须要做一件事情,就是写配置,我发现JOOQ的一个很优秀的地方是,我们不需要写POJO和数据表之间的映射关系到配置文件,工具他会根据数据表自动生成。比如hibernet会写一堆这样的配置文件。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-2.0.4.xsd">
<!-- 配置数据库连接信息,包括驱动,连接字符串,账号等等 -->
<jdbc>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306/jooq_test</url>
<user>root</user>
<password>root</password>
</jdbc>
<generator>
<!-- 代码生成器,用缺省的吧-->
<name>org.jooq.util.DefaultGenerator</name>
<database>
<!-- 数据库类型配置,我用的是mysql -->
<name>org.jooq.util.mysql.MySQLDatabase</name>
<!-- 数据库名字 -->
<inputSchema>jooq_test</inputSchema>
<!-- All elements that are generated from your schema (several Java regular expressions, separated by comma)
Watch out for case-sensitivity. Depending on your database, this might be important! -->
<includes>.*</includes>
<!-- All elements that are excluded from your schema (several Java regular expressions, separated by comma).
Excludes match before includes -->
<excludes></excludes>
</database>
<generate>
<!-- Primary key / foreign key relations should be generated and used.
This will be a prerequisite for various advanced features
Defaults to false -->
<relations>true</relations>
</generate>
<target>
<!-- 代码生成后的包名 -->
<packageName>test.generated</packageName>
<!-- 代码生成的目录 -->
<directory>D:/java_prj/JooqPrj/src</directory>
</target>
</generator>
</configuration>
第二件事就是写测试代码。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.Factory;
import test.generated.tables.Posts;
public class MainTest
{
public static void main(String [] args)
{
Connection conn = null;
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost:3306/jooq_test";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
Factory create = new Factory(conn, SQLDialect.MYSQL);
Result<Record> result = create.select().from(Posts.POSTS).fetch();
for (Record r : result)
{
Long id = r.getValue(Posts.POSTS.ID);
String title = r.getValue(Posts.POSTS.TITLE);
String description = r.getValue(Posts.POSTS.BODY);
System.out.println("ID: " + id + " title: " + title + " desciption: " + description);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ignore)
{
}
}
}
}
}
是不是很简单!!!小项目用这个最合适啦。