[英]JOOQ and Spring
很多人都在使用 jOOQ 和 Spring 或 Spring Boot
Petri Kainulainen 也有一個非常好的教程,解釋了設置項目的每一步,這里:
這是一篇關於如何在 Spring Boot 中使用 jOOQ 的博客文章,當您需要 jOOQ 的商業發行版時特別有用:
我希望將 jOOQ 用作構建器庫,以提供對 Spring 的 JdbcTemplate 和相關類的查詢。 不幸的是,jOOQ 似乎將兩個概念結合到同一組類中:SQL 生成和查詢執行。 就我而言,我想要前者,但想讓 Spring 處理后者。 不過,它確實有效。 例如,您可以執行以下操作(使用 jOOQ 2.x API):
Factory create = new Factory(null, SQLDialect.ORACLE);
getJdbcTemplate().query(
create.select(create.field(ID_COL),
create.field(VALUE_COL))
.from(FOO_TABLE)
.where(create.field(ID_COL).equals("ignored"))
.getSQL(),
myRowMapper,
id);
使用 jOOQ 運行 spring 事務要簡單得多(除非我忘記了什么):
只需將您的數據源包裝到
org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
可選:延遲打開 jdbc 連接,直到第一個實際的 sql 語句發生使用
org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
所以作為一個示例,這樣做是為了創建一個應用了“事務”和“懶惰”的 jOOQ 工廠
DataSource rawDS = /* your actual data source */
// (optional) make access lazy
final DataSource lazyDS = new LazyConnectionDataSourceProxy(rawDataSource);
// make spring transactions available in plain jdbc context
final DataSource txDS = new TransactionAwareDataSourceProxy(lazyDS);
// create jOOQ factory
Factory jooq = new Factory(txDS, /* dialect */, /* settings */)
// voila!
為了使 jOOQ 與 spring 一起工作,您需要做/知道的所有事情:
java.sql.Connection
。因此,對於第一種和第二種情況,我提供了這個要點: https ://gist.github.com/3669307 符合Lukas 的建議。
對於第三種情況,您可以基本上創建工廠的工廠(其中包含DataSource
),也可以使用 spring 組件中的有線DataSource
在每個方法中實例化一個新的Factory
對象。
@Service
public class MyDaoOrService {
@Autowired
private void DataSource dataSource;
@Transactional
public void doSomeJooq(){
Settings s = new Settings();
//You could instead put this jooq configuration xml
s.getExecuteListeners().add("com.snaphop.jooq.SpringExceptionTranslationExecuteListener");
MyGeneratedFactory f = new MyGeneratedFactory(dataSource, s);
f.select(); //etc
}
}
至於設置監聽器,您可以通過 JOOQ 的配置支持來避免編程創建。
我不會介紹如何在 Spring 中設置DataSource
,因為它在無數其他/更好的地方都有介紹。
假設你正在使用 Spring 構建一個 webapp,你可能想要做這樣的事情:
try {
Connection conn = dataSource.getConnection();
try {
// Do something with JOOQ
// No need to use a JdbcTemplate!
}
finally {
if (conn != null) {
conn.close();
}
}
} catch (SQLException e) {
// your error handling
}
您可能希望通過 Spring 的依賴注入獲取 DataSource,因為您的 Web 容器 Tomcat 或其他任何東西都在提供 DataSource 並進行連接池。 在你的一個彈簧配置文件中,你會有類似的東西
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
上述代碼所在的對象(或為該代碼提供數據源的某個對象)可以在 spring 文件中配置以使用數據源實例化它,例如
<bean id="fooService" class="com.fubar.FooServiceImpl">
<constructor-arg ref="dataSource" type="javax.sql.DataSource" />
</bean>
字符串“jdbc/datasource”的部分將對應於 Web 容器中配置的資源名稱。 這會有所不同,但對於 Tomcat,它可能是 Tomcat 主頁下 conf/Catalina/localhost 中的上下文文件,例如,
<?xml version="1.0" encoding="UTF-8"?>
<Context debug="10" reloadable="true" useNaming="true" antiJARLocking="true">
<Resource name="jdbc/datasource" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" validationQuery="SELECT 1"
username="foo" password="fubar" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost/foobase"/>
</Context>
希望這對某人有幫助....
Spring 應用程序上下文配置。
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName">
<value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
</property>
<property name="searchSystemEnvironment">
<value type="boolean">true</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url"
value="jdbc:h2://${user.home}
${file.separator}tracciabilitaCanarini${file.separator}db${file.separator}basedb"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</bean>
<bean id="datasourceConnection"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
lazy-init="true" depends-on="dataSource">
<property name="targetObject">
<ref bean="dataSource"/>
</property>
<property name="targetMethod">
<value>getConnection</value>
</property>
</bean>
<bean id="publicFactory" class="dbLayer.db.PublicFactory" lazy-init="true"
depends-on="datasourceConnection" >
<constructor-arg index="0" ref="datasourceConnection" />
</bean>
它將使用給定的連接自動填充公共工廠(是的,它可以是池連接,自動關閉等,請參閱 DriverManagerDataSource 類以獲得更詳細的配置)。 現在,publicFactory。 注意:不需要修改jOOQ生成的原始公共工廠。
/**
* This class is generated by jOOQ
*/
package dbLayer.db;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = {"http://www.jooq.org", "2.0.5"},
comments = "This class is generated by jOOQ")
public class PublicFactory extends org.jooq.util.h2.H2Factory {
private static final long serialVersionUID = -1930298411;
/**
* Create a factory with a connection
*
* @param connection The connection to use with objects created from this factory
*/
public PublicFactory(java.sql.Connection connection) {
super(connection);
}
/**
* Create a factory with a connection and some settings
*
* @param connection The connection to use with objects created from this factory
* @param settings The settings to apply to objects created from this factory
*/
public PublicFactory(java.sql.Connection connection, org.jooq.conf.Settings settings) {
super(connection, settings);
}
}
最后,只需致電工廠即可。
PublicFactory vs = (PublicFactory) SpringLoader.getBean("publicFactory");
SimpleSelectQuery<VersionRecord> sq = vs.selectQuery(dbLayer.db.tables.Version.VERSION);
VersionRecord v = null;
try {
v = sq.fetchAny();
} catch (Exception e) {
log.warn("Seems that version table does not exists!", e);
}
完畢!
對於 Java 配置(Spring Boot 的默認配置),您可以使用以下代碼:
/* JOOQ Configuration */
@Bean
public DataSourceConnectionProvider dataSourceConnectionProvider() {
return new DataSourceConnectionProvider(dataSource());
}
@Bean
public DefaultConfiguration defaultConfiguration() {
DefaultConfiguration defaultConfiguration = new DefaultConfiguration();
defaultConfiguration.setConnectionProvider(dataSourceConnectionProvider());
defaultConfiguration.setSQLDialect(SQLDialect.POSTGRES);
return defaultConfiguration;
}
@Bean
public DSLContext dslContext() {
return new DefaultDSLContext(defaultConfiguration());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.