我正在使用java,spring jdbc模板将n条记录插入到两个表中.有些像这样
假设正确配置了daos.xml.
ApplicationContext ctxt = new ClassPathXmlApplicationContext("daos.xml");
JdbcTemplate template = (JdbcTemplate) ctxt.getBean("jdbcTemplate");
final List<Person> list = new ArrayList<>();
final List<Role> roles = new ArrayList<>();
for(int i =1; i<=100; i++){
Person item = new Person();
item.setFirstName("Naveen" + i);
item.setLastName("kumar" + i);
item.setDescription("D" + i);
list.add(item);
Role role = new Role();
role.setName("Admin");
role.setCode("c" + i);
roles.add(role);
}
String sql = "insert into person(first_name, last_name, description) values(?,?,?)";
int[] arr = template.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws …Run Code Online (Sandbox Code Playgroud) 我有一个集成测试课UserController.以下课程的内容如下:
// imports...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Transactional
@Rollback
public class UserControllerTests {
private static final String ENDPOINT = "/v1/users";
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private ApplicationProperties applicationProperties;
@Test
public void test_user_create() {
String token = login("test", "test");
HttpEntity<UserRequest> request = createRequest(token, "admin", "admin");
ResponseEntity<User> response = restTemplate.exchange(ENDPOINT, HttpMethod.POST, request, User.class);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
}
private HttpEntity createRequest(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", String.format("Bearer %s", token));
return new HttpEntity(headers);
}
private HttpEntity<UserRequest> createRequest(String token, String …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用params for Spring Boot JDBC进行日志SQL查询,但它没有在日志中打印详细信息.我正在使用Spring Boot 1.5.8版本.请帮我解决这个问题.
application.properties:
spring.datasource.url=url
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
logging.level.org.springframework.jdbc.core.JdbcTemplate=debug
spring.datasource.type = com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=2
Run Code Online (Sandbox Code Playgroud)
库:
@Repository
public class DataRepository {
private static Logger log = LoggerFactory.getLogger(DataRepository.class);
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
public Data findDataObjet() throws Exception {
Map<String, Object> parameters = new HashMap<>();
parameters.put("id1", "mike");
parameters.put("id2", new Long(1));
String sqlString = "select * from table1 where id1 = ":id" and id2 = :id2";
log.info("Query:" + sqlString);//this log is printing
Data extObj = jdbcTemplate.query(sqlString, parameters, (rs) -> { …Run Code Online (Sandbox Code Playgroud) 我们正在使用 java(Spring 和 Spring Boot)开发微服务,对 Oracle DB 的访问是通过 JDBC Oracle Driver 完成的。
问题是我们的 DBA 只能在 Oracle 端看到连接了“JDBC 瘦客户端”。连接的应用程序没有更好的逻辑表示。如果没有这样的识别,就很难知道哪个微服务可能表现不佳。其他非 JDBC 客户端使用主机名清楚地标识自己。
有什么方法可以更改标识字符串,使其代表源应用程序/进程的明确标识?
注意:我们的系统在使用容器的 Cloud Foundry 上运行,因此实际上不可能提供机器名称或类似的名称 - 首选逻辑应用程序名称。
谢谢
我正在使用 Postgresql 和 spring boot 2.0.4。尝试一个接一个地执行查询时会引发以下错误。我执行了以下查询,并且计数不断增加。
SELECT COUNT(*) FROM pg_stat_activity WHERE state ILIKE '%idle%';
Run Code Online (Sandbox Code Playgroud)
我已经将这些属性和依赖项用于连接池。然而,它给出了同样的错误
spring.datasource.dbcp2.initial-size=10
spring.datasource.dbcp2.max-total=25
spring.datasource.dbcp2.pool-prepared-statements=true
spring.datasource.hikari.max-lifetime=600000
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
错误:
2018-09-27 16:43:25.481 WARN 9085 --- [nio-8081-exec-4] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@2a84e649 (This connection has been closed.)
2018-09-27 16:43:40.490 WARN 9085 --- [nio-8081-exec-4] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@9faf6ae (This connection has been closed.)
2018-09-27 16:44:00.934 WARN 9085 --- [nio-8081-exec-4] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@24723851 …Run Code Online (Sandbox Code Playgroud) 在 Spring 中,使用DriverManagerDataSource和SimpleDriverDataSource来创建一个新的数据源(给定它的 driverClassName、url、用户名和密码)有什么区别?
例如,使用 DriverManagerDataSource 您可以执行以下操作:
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
Run Code Online (Sandbox Code Playgroud)
使用 SimpleDriverDataSource 您可以执行以下操作:
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
Class<? extends Driver> driver = (Class<? extends Driver>) Class.forName(driverClassName);
dataSource.setDriverClass(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
Run Code Online (Sandbox Code Playgroud) 我对 Spring 世界很陌生。我使用application.properties来设置不同的端口值。如何注释 application.properties 文件中的某些代码?
我一直在尝试让 Quartz 在 Spring Boot 中使用 R2DBC 时工作。到目前为止,我还没有弄清楚如何做到这一点。这是因为当创建 JDBC 数据源时,它会尝试初始化我的 R2DBC 存储库,但它无法执行此操作,因为 R2DBC 本质上是反应性的,而 JDBC 本质上是阻塞的。
我考虑过的替代方案
相关 Gradle 依赖项
dependencies {
implementation("io.projectreactor.netty:reactor-netty:0.9.7.RELEASE")
implementation("org.springframework.boot:spring-boot-starter-data-r2dbc")
implementation("org.springframework.boot:spring-boot-starter-quartz")
implementation("org.springframework.boot:spring-boot-starter-data-jdbc")
runtimeOnly("com.h2database:h2")
implementation("io.r2dbc:r2dbc-h2:0.8.3.RELEASE")
}
Run Code Online (Sandbox Code Playgroud)
我当前的石英配置
@Configuration
class QuartzConfig {
@Bean
@QuartzDataSource
fun dataSource(props: DataSourceProperties): DataSource {
return props.initializeDataSourceBuilder().type(HikariDataSource::class.java).build()
}
}
Run Code Online (Sandbox Code Playgroud)
相关R2DBC配置:
abstract class R2DbcConfiguration : AbstractR2dbcConfiguration() {
override fun getCustomConverters(): MutableList<Any> {
return mutableListOf(
// some custom converters
)
}
@Bean
fun connectionFactoryInitializer( …Run Code Online (Sandbox Code Playgroud) SQL 的一项简单优化是重用准备好的语句。您会产生一次解析成本,然后可以PreparedStatement在循环中重用该对象,只需根据需要更改参数即可。Oracle 的 JDBC 教程和许多其他地方都清楚地记录了这一点。
Spring 5 使用时JdbcTemplate似乎使这变得不可能。所有处理 s 的JdbcTemplate查询和更新方法都归结PreparedStatementCreator为一种execute方法。这是该方法的完整代码。
public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
throws DataAccessException {
Assert.notNull(psc, "PreparedStatementCreator must not be null");
Assert.notNull(action, "Callback object must not be null");
if (logger.isDebugEnabled()) {
String sql = getSql(psc);
logger.debug("Executing prepared SQL statement" + (sql != null ? " [" + sql + "]" : ""));
}
Connection con = DataSourceUtils.getConnection(obtainDataSource());
PreparedStatement ps = null;
try { …Run Code Online (Sandbox Code Playgroud) 我有一个 Spring Boot 应用程序 (v2.1.5),它使用 JPA (Hibernate) 连接到 Postgres DB。Spring Boot 使用 HikariCP 进行连接池。在我的生产环境中,我看到以下查询每隔几秒执行一次,无论数据库活动如何(几乎就像它们是某种运行状况检查?):
SET application_name = 'PostgreSQL JDBC Driver'
Run Code Online (Sandbox Code Playgroud)
我正在努力弄清楚为什么这些查询如此频繁地执行,以及是否可以避免它们,因为在我的本地环境中,仅在对数据库执行查询时才执行上述语句。我仍然不明白为什么,但与生产相比,它的频率较低且行为不同。
这些询问有必要吗?它们可以避免吗?谢谢。
更新:
以下是 Spring boot 应用程序使用 HikariCP 连接到的数据库收到的查询的屏幕截图。时间显示为“刚刚”,因为显示的所有查询仅相隔约 0.5 秒,并且都在“当前分钟”内。
spring-jdbc ×10
spring ×6
java ×5
spring-boot ×4
jdbc ×3
postgresql ×3
hikaricp ×2
datasource ×1
eclipse ×1
junit ×1
kotlin ×1
log4j ×1
mysql ×1
oracle ×1
quartz ×1
spring-data ×1