我是准备好的语句的新手,我正在尝试使用 jdbcTemplate 来使用基本插入和更新,这也工作正常,但我希望在控制台中打印 sql 查询的日志,但我不知道如何实现这一点。我已在 application.properties 文件中添加了必需的属性,但它不起作用。请通过提供一些适当的建议或引用链接来帮助我,这可能会解决我的问题。提前致谢...
示例配置.java
@Configuration
public class SampleConfiguration
{
@Bean
public DataSource mysqlDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:hsql://localhost/");
dataSource.setUsername("SA");
dataSource.setPassword("");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource)
{
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
}
SampleService.java
@Service
public interface SampleService
{
public int insert();
public long getCount();
}
SampleServiceImpl.java
@Service
public class SampleServiceImpl implements SampleService
{
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public int insert()
{
return jdbcTemplate.update("insert into batch values(?,?)","field1","field2");
}
@Override
public long getCount()
{
return jdbcTemplate.queryForObject("select count(*) from batch", Long.class);
}
}
SpringjdbcApplication.java
@SpringBootApplication
public class SpringjdbcApplication
{
public static void main(String[] args)
{
ApplicationContext context = SpringApplication.run(SpringjdbcApplication.class, args);
SampleService service = context.getBean(SampleService.class);
System.err.println("The number of rows inserted = "+service.insert());
System.err.println("The count of batch class is = "+service.getCount());
}
}
实体.java
@Entity
public class Batch implements Serializable
{
private static final long serialVersionUID = -5687736664713755991L;
@Id
@Column(name="field1")
private String field1;
@Column(name="field2")
private String field2;
... getter, setter and no-arg constructor
}
应用程序属性
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql=trace
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
我想知道如何在控制台上打开 sql 语句日志记录以及如何设置其他属性,例如关闭或打开自动提交???
您应该将其添加到属性文件中
logging.level.org.springframework.jdbc.core = TRACE
这将启用 Spring Jdbc 日志
我是一名优秀的程序员,十分优秀!