【发布时间】:2019-02-11 13:49:41
【问题描述】:
情况:
我安排了一个 15 分钟长的任务。它重新生成 2 个表。我想在 ONE 交易中进行,但是使用 @Transational,repo 调用有 2 个不同的交易,用于很多 repo 调用。
这是一个带有 postgres 的 spring boot 2 项目。
repos 有可能有不同的连接吗?
(我删除并简化了一些 DI。)
代码示例:
@Scheduled(...)
public class ScheduledTaskRunner
{
@Transactional
public void run()
{
aService.parseXML();
bService.parseCSV();
}
}
@Service
public class AService
{
public function parseXML()
{
for (Node node : parserMethodSomewhere())
{
aRepository.save(node.getDataA(), node.getDataB());
}
}
}
@Service
public class BService
{
public function parseCSV()
{
for (Node node : parserMethodSomewhere())
{
bRepository.save(node.getDataA(), node.getDataB());
}
}
}
@Service
public class ConnectionService
{
@Autowired
private DataSource dataSource;
private Connection connection = null;
public Connection getConnection() throws SQLException
{
if (null == connection)
{
connection = dataSource.getConnection();
}
return connection;
}
}
@Service
public class JooqService
{
@Autowired
private Connection connection;
private DSLContext dslContext = null;
public DSLContext createQueryBuilder()
{
if (null == dslContext)
{
this.dslContext = DSL.using(connection, SQLDialect.POSTGRES);
}
return dslContext;
}
}
@Repository
public abstract class AbstractRepository
{
@Autowired
private JooqService jooqService;
DSLContext createQueryBuilder()
{
return jooqService.createQueryBuilder();
}
}
public function ARepository extends AbstractRepository
{
public function save(int a, int b)
{
createQueryBuilder().insertInto(table, table.a, table.b).values(a, b).execute();
}
}
public function BRepository extends AbstractRepository
{
public function save(int a, int b)
{
createQueryBuilder().insertInto(table, table.a, table.b).values(a, b).execute();
}
}
============================================== 变通方法 - 解决方案:
@Scheduled(...)
public class ScheduledTaskRunner
{
// @Transactional
public void run()
{
jooqService.createQueryBuilder().transaction(
(configuration) ->
{
aService.parseXML();
bService.parseCSV();
}
);
}
}
【问题讨论】:
标签: postgresql spring-boot transactions jooq