当前位置:网站首页>PostgreSQL manually creates hikaridatasource to solve the error cannot commit when autocommit is enabled
PostgreSQL manually creates hikaridatasource to solve the error cannot commit when autocommit is enabled
2022-07-29 08:17:00 【Persistence is an attitude】
PostgreSQL establish HikariDataSource Resolve errors autoCommit

problem
- The project is to use jhipster Built , Use liquibase Manage database connections
- What we use PostgreSQL database , Because of business needs , Need to add a new ClickHouse database , But these two
DataSourceCause program error
solve
- First , You are right PostgreSQL Database connection , Explicitly declare . stay
DatabaseConfigurationin , Explicitly declare@Bean("springDataSource")And set up@Primary, Give priority to loading and using pg
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@EnableJpaRepositories({ "com.xxx.analysis.repository" })
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class);
/**
* PG data source
* Due to manual injection CK data source , So you need to explicitly declare here PG The priority of data source is springDataSource
* @param properties yml Data source configuration in
* @return dataSource
*/
@Primary // Default preference
@Bean("springDataSource") // Inject springDataSource object
@ConfigurationProperties(prefix = "spring.datasource") // Inject dspringDataSource Object read configuration file ,spring.datasource The prefix , After that, the fields are matched with the attributes of the entity class, such as content
public DataSource dataSource(DataSourceProperties properties) {
logger.info("init master data source:{}", properties.determineDatabaseName());
return DataSourceBuilder.create().build();
}
}
- In this way, there is no error when the program starts , But there are problems in using , Report errors
org.springframework.orm.jpa.JpaSystemException: Unable to commit against JDBC Connection; nested exception is org.hibernate.TransactionException: Unable to commit against JDBC Connection
Caused by: org.hibernate.TransactionException: Unable to commit against JDBC Connection
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:92)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:282)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562)
... 155 common frames omitted
Caused by: org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.
at org.postgresql.jdbc.PgConnection.commit(PgConnection.java:872)
at com.zaxxer.hikari.pool.ProxyConnection.commit(ProxyConnection.java:387)
at com.zaxxer.hikari.pool.HikariProxyConnection.commit(HikariProxyConnection.java)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:86)
... 158 common frames omitted
- After using annotation declaration instead ,
autoCommitIt didn't work , After debugging, I foundDataSourcePropertiesOnly some parameters are received , andautoCommitNot in there - Can't , I have to accept the parameters myself , Create your own connection initialization
HikariDataSource了 , The final configuration and code are as follows
The configuration file
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:postgresql://192.168.1.50:5432/june
username: postgres
password: postgres
hikari:
poolName: Hikari
autoCommit: false
maximum-pool-size: 100
connection-timeout: 60000
idle-timeout: 400000
minimum-idle: 10
max-lifetime: 480000
connection-test-query: SELECT 1
Code
package com.xxx.analysis.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
@Configuration
@EnableJpaRepositories({
"com.xxx.analysis.repository" })
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class);
@Value("${spring.datasource.hikari.poolName}")
private String poolName;
@Value("${spring.datasource.hikari.autoCommit}")
private boolean autoCommit;
@Value("${spring.datasource.hikari.connection-timeout}")
private Integer connectionTimeout;
@Value("${spring.datasource.hikari.idle-timeout}")
private Integer idleTimeout;
@Value("${spring.datasource.hikari.max-lifetime}")
private Integer maxLifetime;
@Value("${spring.datasource.hikari.minimum-idle}")
private Integer minimumIdle;
@Value("${spring.datasource.hikari.maximum-pool-size}")
private Integer maximumPoolSize;
@Value("${spring.datasource.hikari.connection-test-query}")
private String connectionTestQuery;
/** * PG data source * Due to manual injection CK data source , So you need to explicitly declare here PG The priority of data source is springDataSource * @param properties yml Data source configuration in * @return dataSource */
@Primary // Default preference
@Bean("springDataSource") // Inject springDataSource object
@ConfigurationProperties(prefix = "spring.datasource") // Inject springDataSource Object read configuration file ,spring.datasource The prefix , After that, the fields are matched with the attributes of the entity class, such as content
public DataSource dataSource(DataSourceProperties properties) {
HikariDataSource dataSource = new HikariDataSource(getConfig(properties));
if (StringUtils.hasText(properties.getName())) {
dataSource.setPoolName(properties.getName());
}
return dataSource;
}
/** * according to yml Configuration settings HikariConfig * @param properties * @return */
private HikariConfig getConfig(DataSourceProperties properties) {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(properties.getUrl());
hikariConfig.setUsername(properties.getUsername());
hikariConfig.setPassword(properties.getPassword());
hikariConfig.setMaximumPoolSize(maximumPoolSize);
hikariConfig.setConnectionTestQuery(connectionTestQuery);
hikariConfig.setPoolName(poolName);
hikariConfig.setAutoCommit(autoCommit);
hikariConfig.setConnectionTimeout(connectionTimeout);
hikariConfig.setIdleTimeout(idleTimeout);
hikariConfig.setMaxLifetime(maxLifetime);
hikariConfig.setMinimumIdle(minimumIdle);
hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
return hikariConfig;
}
}
边栏推荐
- The difference between torch.tensor and torch.tensor
- Hal library learning notes - 8 concept of serial communication
- AES 双向加密解密工具
- Ws2812b color lamp driver based on f407zgt6
- Privacy is more secure in the era of digital RMB
- Some tools, plug-ins and software links are shared with you~
- STM32 MDK (keil5) contents mismatch error summary
- ROS tutorial (Xavier)
- [beauty of software engineering - column notes] 24 | technical debt: continue to make do with it, or overthrow it and start over?
- Unity - default rendering pipeline - sculpt shader
猜你喜欢

Intelligent shelf safety monitoring system
![[beauty of software engineering - column notes] 21 | architecture design: can ordinary programmers also implement complex systems?](/img/db/ef33a111bcb543f9704706049bccc2.png)
[beauty of software engineering - column notes] 21 | architecture design: can ordinary programmers also implement complex systems?

What constitutes the smart charging pile system?

Simplefoc parameter adjustment 3-pid parameter setting strategy

【学术相关】为什么很多国内学者的AI的论文复现不了?

Windows 安装 MySQL 5.7详细步骤

Detailed steps of installing MySQL 5.7 for windows

DAC0832 waveform generator based on 51 single chip microcomputer

Cyberpunk special effect shader

Simplefoc+platformio stepping on the path of the pit
随机推荐
DC motor control system based on DAC0832
Usage of torch.tensor.to
Unity多人联机框架Mirro学习记录(一)
Random lottery turntable wechat applet project source code
Implementation of simple matcap+fresnel shader in unity
(Video + graphic) machine learning introduction series - Chapter 5 machine learning practice
Unity multiplayer online framework mirror learning record (I)
Nrf52832-qfaa Bluetooth wireless chip
Implementation of simple cubecap+fresnel shader in unity
Segment paging and segment page combination
Operator overloading
Security baseline of network security
Unity beginner 3 - enemy movement control and setting of blood loss area (2D)
STM32 printf problem summary semihosting microlib understanding
Some tools, plug-ins and software links are shared with you~
[beauty of software engineering - column notes] 30 | make good use of source code management tools to make your collaboration more efficient
Qt/pyqt window type and window flag
NFC two-way communication 13.56MHz contactless reader chip -- si512 replaces pn512
[noi simulation] computational geometry (convex hull, violence, and search set)
Inclination monitoring solution of Internet of things