[QueryDSL / Spring] java.lang.IllegalStateException:Connection不是事务性的

时间:2015-12-10 10:06:24

标签: java spring querydsl transactional

我写的是Spring + Vaadin应用程序。我想添加QueryDSL来访问db(Oracle)。我查看了文档(http://docs.spring.io/spring-data/jdbc/docs/current/reference/html/core.querydsl.html),我读到Spring建议使用标准的QueryDSL api。我依照自己的意愿对我的项目进行了抨击:

<dependency>
    <groupId>com.mysema.querydsl</groupId>
    <artifactId>querydsl-sql-spring</artifactId>
    <version>${querydsl.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>
    <groupId>com.mysema.querydsl</groupId>
    <artifactId>querydsl-sql</artifactId>
    <version>${querydsl.version}</version>
</dependency>

我的 beans.xml 如下:

<bean id="dataSourceOracle" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${db.oracle.driverClassName}" />
    <property name="url" value="${db.oracle.url}"/>
    <property name="username" value="${db.oracle.username}" />
    <property name="password" value="${db.oracle.password}" />
    <property name="defaultAutoCommit" value="false" />
</bean>

在我的DatabaseFacade实现中,我执行以下配置:

private SQLQueryFactory query;

@Autowired
@Qualifier("DataSource")
public void setDataSource(DataSource dataSource) {
    Provider<Connection> provider = new SpringConnectionProvider(dataSource);
    Configuration configuration = new Configuration(new OracleTemplates());
    configuration.setExceptionTranslator(new SpringExceptionTranslator());
    query = new SQLQueryFactory(configuration, provider);
}

不幸的是每次我开始申请时都会得到:

10:29:54.490 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
10:29:56.231 [main] ERROR c.r.i.k.b.impl.DatabaseFacadeImpl - Error happend in com.roche.icc.kps.backend.impl.DatabaseFacadeImpl.getEditableKPSStores
10:29:56.234 [main] ERROR c.r.i.k.b.impl.DatabaseFacadeImpl - Connection is not transactional
java.lang.IllegalStateException: Connection is not transactional
    at com.mysema.query.sql.spring.SpringConnectionProvider.get(SpringConnectionProvider.java:45) ~[querydsl-sql-spring-3.7.0.jar:na]
    at com.mysema.query.sql.spring.SpringConnectionProvider.get(SpringConnectionProvider.java:33) ~[querydsl-sql-spring-3.7.0.jar:na]
    at com.mysema.query.sql.SQLQueryFactory.query(SQLQueryFactory.java:63) ~[querydsl-sql-3.7.0.jar:na]
    at com.mysema.query.sql.SQLQueryFactory.query(SQLQueryFactory.java:28) ~[querydsl-sql-3.7.0.jar:na]
    at com.mysema.query.sql.AbstractSQLQueryFactory.from(AbstractSQLQueryFactory.java:54) ~[querydsl-sql-3.7.0.jar:na]

有没有人遇到过这个问题?我应该使用不同的DataSource(Atomikos?)?

感谢您的帮助!

卡米尔

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题。

问题是QueryDSL期望数据源连接在事务中。所以要么你必须明确地开始交易并处理它,要么IOC容器应该为你做。

在这种情况下,您很可能在应该启动事务的任何应用程序层(服务/存储库)中没有@Transactional注释。

将@Transactional注释添加到您的dao或服务层以解决问题。

帮助我的链接是 https://groups.google.com/forum/#!topic/querydsl/_PqMek79TZE

一个示例项目。 https://github.com/querydsl/querydsl/tree/master/querydsl-examples/querydsl-example-sql-spring

更新

这是示例项目中DaoImpl的方式 请注意类级别中的@Transactional注释。

@Transactional
public class CustomerDaoImpl implements CustomerDao {

@Inject
SQLQueryFactory queryFactory;

final QBean<CustomerAddress> customerAddressBean = bean(CustomerAddress.class,
        customerAddress.addressTypeCode, customerAddress.fromDate, customerAddress.toDate,
        bean(Address.class, address.all()).as("address"));

final QBean<Customer> customerBean = bean(Customer.class,
        customer.id, customer.name,
        bean(Person.class, person.all()).as("contactPerson"),
        GroupBy.set(customerAddressBean).as("addresses"));

@Override
public Customer findById(long id) {
    List<Customer> customers = findAll(customer.id.eq(id));
    return customers.isEmpty() ? null : customers.get(0);
}

@Override
public List<Customer> findAll(Predicate... where) {
    return queryFactory.from(customer)
        .leftJoin(customer.contactPersonFk, person)
        .leftJoin(customer._customer3Fk, customerAddress)
        .leftJoin(customerAddress.addressFk, address)
        .where(where)
        .transform(GroupBy.groupBy(customer.id).list(customerBean));
}

@Override
public Customer save(Customer c) {
    Long id = c.getId();

    if (id == null) {
        id = queryFactory.insert(customer)
                .set(customer.name, c.getName())
                .set(customer.contactPersonId, c.getContactPerson().getId())
                .executeWithKey(customer.id);
        c.setId(id);
    } else {
        queryFactory.update(customer)
            .set(customer.name, c.getName())
            .set(customer.contactPersonId, c.getContactPerson().getId())
            .where(customer.id.eq(c.getId()))
            .execute();

        // delete address rows
        queryFactory.delete(customerAddress)
            .where(customerAddress.customerId.eq(id))
            .execute();
    }

    SQLInsertClause insert = queryFactory.insert(customerAddress);
    for (CustomerAddress ca : c.getAddresses()) {
        if (ca.getAddress().getId() == null) {
            ca.getAddress().setId(queryFactory.insert(address)
                .populate(ca.getAddress())
                .executeWithKey(address.id));
        }
        insert.set(customerAddress.customerId, id)
            .set(customerAddress.addressId, ca.getAddress().getId())
            .set(customerAddress.addressTypeCode, ca.getAddressTypeCode())
            .set(customerAddress.fromDate, ca.getFromDate())
            .set(customerAddress.toDate, ca.getToDate())
            .addBatch();
    }
    insert.execute();

    c.setId(id);
    return c;
}

@Override
public long count() {
    return queryFactory.from(customer).fetchCount();
}

@Override
public void delete(Customer c) {
    // TODO use combined delete clause
    queryFactory.delete(customerAddress)
        .where(customerAddress.customerId.eq(c.getId()))
        .execute();

    queryFactory.delete(customer)
        .where(customer.id.eq(c.getId()))
        .execute();
}

}

在您的情况下,注释应放在DatabaseFacade实现中。我假设您的Spring应用程序也配置了事务管理器。

答案 1 :(得分:1)

我遇到了这个问题,我可以解决此问题,如下所示:

除此之外你应该为你的dao / Repository类标记@Transactional注释,你还必须为你的spring java配置类标记@EnableTransactionManagement,就像下面一样

@Configuration
@EnableTransactionManagement
public class QuerydslConfiguration {
    @Bean
    public DataSource dataSource() {
        // implement your datasource
    }

    @Bean
    @Qualifier("transactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public com.querydsl.sql.Configuration initConfiguration() {
        // check the spring integration section
    }

    @Bean
    public SQLQueryFactory queryFactory() {
        // check the spring integration section
    }
}

@Repository
@Transactional
public class PaymentDAO {
}

spring integration section

您还可以在spring上下文xml中声明EnableTransactionManagement
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>