Querydsl + Spring + Transactional忽略

时间:2016-02-19 18:53:45

标签: java spring postgresql transactions querydsl

我想确认回滚行为,但我无法让它发挥作用。

我有一个包含以下表格的postgres数据库:

select * from cat;

               pkid                   | name  
--------------------------------------+-------
 c75d6e8b-6aff-4214-ad45-d17db254857b | Abbey


select * from toy;

                 pkid                 |     name      |                description                
--------------------------------------+---------------+-------------------------------------------
 dda72782-a1aa-4c0e-9cf6-a408db58a1ae | Laser pointer | Red laser.
 f4d7e67d-1b26-4d8d-bb98-1a5c69f3cb49 | String        | Colored string attached to a plastic rod.

select * from cattoy;

pkid  | fkcat | fktoy 
------+-------+-------

我创建了一个CatService实现,其想法是你可以创建一个猫,玩具,并将该玩具与该猫联系起来。如果3个操作中的任何一个失败,我希望它们全部回滚。

DefaultCatService.java:

import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bonkeybee.dao.CatDao;
import com.bonkeybee.dao.CatToyDao;
import com.bonkeybee.dao.ToyDao;
import com.bonkeybee.querydsl.Cat;
import com.bonkeybee.querydsl.Cattoy;
import com.bonkeybee.querydsl.Toy;

@Inject
private CatDao catDao;

@Inject
private CatToyDao catToyDao;

@Inject
private ToyDao toyDao;

@Override
@Transactional
public UUID createCat(final Cat cat){
    LOG.debug("Creating cat");
    UUID catPkid = catDao.createCat(cat);

    Toy toy = new Toy();
    toy.setName("Box");
    toy.setDescription("Cardboard box.");
    toy.setPkid(toyDao.createToy(toy));

    Cattoy catToy = new Cattoy();
    catToy.setFkcat(catPkid);
    catToy.setFktoy(toy.getPkid());
    catToyDao.createCatToy(catToy);

    return catPkid;
}

我已经使用基本的CRUD操作为每个表创建了DAO及其实现。

CatDaoJdbc.java:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bonkeybee.querydsl.Cat;
import com.bonkeybee.querydsl.QCat;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimplePath;
import com.querydsl.core.types.dsl.StringPath;
import com.querydsl.sql.SQLQueryFactory;

private static final QCat CAT = QCat.cat;
private static final SimplePath<Object> CAT_PKID = CAT.pkid;
private static final StringPath CAT_NAME = CAT.name;

@Inject
private SQLQueryFactory sqlQueryFactory;

@Override
public UUID createCat(final Cat cat) {
    UUID catPkid = UUID.randomUUID();
    sqlQueryFactory.insert(CAT)
        .columns(CAT_PKID, CAT_NAME)
        .values(catPkid, cat.getName())
        .execute();
    return catPkid;
}

ToyDaoJdbc.java

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bonkeybee.querydsl.QToy;
import com.bonkeybee.querydsl.Toy;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimplePath;
import com.querydsl.core.types.dsl.StringPath;
import com.querydsl.sql.SQLQueryFactory;

private static final QToy TOY = QToy.toy;
private static final SimplePath<Object> TOY_PKID = TOY.pkid;
private static final StringPath TOY_NAME = TOY.name;
private static final StringPath TOY_DESCRIPTION = TOY.description;

@Inject
private SQLQueryFactory sqlQueryFactory;

@Override
public UUID createToy(Toy toy) {
    UUID toyPkid = UUID.randomUUID();
    sqlQueryFactory.insert(TOY)
        .columns(TOY_PKID, TOY_NAME, TOY_DESCRIPTION)
        .values(toyPkid, toy.getName(), toy.getDescription())
        .execute();
    return toyPkid;
}

CatToyDaoJdbc.java:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bonkeybee.querydsl.Cattoy;
import com.bonkeybee.querydsl.QCat;
import com.bonkeybee.querydsl.QCattoy;
import com.bonkeybee.querydsl.QToy;
import com.bonkeybee.querydsl.Toy;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimplePath;
import com.querydsl.sql.SQLQueryFactory;

@Override
public UUID createCatToy(Cattoy catToy) {
    throw new RuntimeException("Simulating exception");
}

Main.java:

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.bonkeybee.querydsl.Cat;
import com.bonkeybee.querydsl.Cattoy;
import com.bonkeybee.querydsl.Toy;
import com.bonkeybee.service.CatService;
import com.bonkeybee.service.CatToyService;
import com.bonkeybee.service.ToyService;

public static void main(String[] args) {
    try (ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class)) {
        CatService catService = applicationContext.getBean(CatService.class);

        Cat newCat = new Cat();
        newCat.setName(DORA);
        newCat.setPkid(catService.createCat(newCat));
    }
}

ApplicationConfiguration.java:

import java.beans.PropertyVetoException;

import javax.inject.Inject;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.querydsl.sql.PostgreSQLTemplates;
import com.querydsl.sql.SQLQueryFactory;

@Configuration
@EnableTransactionManagement
@ComponentScan("com.bonkeybee")
public class ApplicationConfiguration {

    @Bean
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(JDBC_DRIVER);
        comboPooledDataSource.setJdbcUrl(JDBC_URL);
        comboPooledDataSource.setUser(USER);
        comboPooledDataSource.setPassword(PASSWORD);
        comboPooledDataSource.setMinPoolSize(MIN_POOL_SIZE);
        comboPooledDataSource.setInitialPoolSize(MIN_POOL_SIZE);
        comboPooledDataSource.setMaxPoolSize(MAX_POOL_SIZE);
        return comboPooledDataSource;
    }

    @Bean
    @Inject
    public PlatformTransactionManager getPlatformTransactionManager(final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public com.querydsl.sql.Configuration getQueryDslConfiguration() {
        return new com.querydsl.sql.Configuration(PostgreSQLTemplates.builder().build());
    }

    @Bean
    @Inject
    public SQLQueryFactory getSQLQueryFactory(final com.querydsl.sql.Configuration configuration, final DataSource dataSource) {
        return new SQLQueryFactory(configuration, dataSource);
    }
}

当Main调用catService.createCat()时,会创建cat和toy,然后按预期抛出RuntimeException,但是之后对表的检查会显示创建的新cat和新玩具而不是回滚。请这样,帮助我确保没有猫没玩过&gt;:3

编辑:按要求添加导入

3 个答案:

答案 0 :(得分:0)

由于您的交易涉及多个数据库请求,因此您必须指定 持久化上下文为PersistenceContextType.EXTENDED,这意味着它可以承受多个请求。

答案 1 :(得分:0)

你必须拥有一个实体经理,然后从中获取交易对象 获得事务管理器后,开始新事务,执行所有数据库操作然后提交。
以下是示例

EntityManagerFactory emf = ...
EntityManager em = emf.createEntityManager(PersistenceContextType.EXTENDED);

杂志mag1 = em.find(Magazine.class,magId);
杂志mag2 = em.find(Magazine.class,magId);
em.getTransaction()()开始。 :

。em.getTransaction()结束();

答案 2 :(得分:0)

经过多次搜索解决后,有两个配置问题。

首先:默认情况下,事务管理器bean spring查找应命名为&#34; transactionManager&#34;否则你必须明确设置名称。

第二:我添加了依赖于&#34; querydsl-sql-spring&#34; artifact并更改了我的SQLQueryFactory以使用SpringConnectionProvider而不是DataSource bean(从querydsl人员的this示例中找到)。以下是最终配置:

@Configuration
@EnableTransactionManagement
@ComponentScan("com.bonkeybee")
public class ApplicationConfiguration {

    @Bean
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(JDBC_DRIVER);
        comboPooledDataSource.setJdbcUrl(JDBC_URL);
        comboPooledDataSource.setUser(USER);
        comboPooledDataSource.setPassword(PASSWORD);
        comboPooledDataSource.setMinPoolSize(MIN_POOL_SIZE);
        comboPooledDataSource.setInitialPoolSize(MIN_POOL_SIZE);
        comboPooledDataSource.setMaxPoolSize(MAX_POOL_SIZE);
        return comboPooledDataSource;
    }

    @Inject
    @Bean(name = "transactionManager")
    public PlatformTransactionManager getPlatformTransactionManager(final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public com.querydsl.sql.Configuration getQueryDslConfiguration() {
        return new com.querydsl.sql.Configuration(PostgreSQLTemplates.builder().build());
    }

    @Inject
    @Bean
    public SQLQueryFactory getSQLQueryFactory(final com.querydsl.sql.Configuration configuration, final DataSource dataSource) {
        Provider<Connection> provider = new SpringConnectionProvider(dataSource);
        return new SQLQueryFactory(configuration, provider);
    }
}

感谢querydsl人们提供了一个很酷的lib。