Spring Data不记录findById

时间:2019-12-28 13:39:29

标签: java spring spring-boot spring-data-jpa

已创建Customer实体和存储库:

public interface CustomerRepository extends CrudRepository<Customer, Long> {
}

和保存并选择实体的bean:

@Component
public class BeanClass
{
  @Autowired
  CustomerRepository repository;

  @Transactional
  public void tran()
  {
    Customer entity = new Customer("Jack3", "Bauer");
    Customer save1 = repository.save(entity);
    Optional<Customer> byId = repository.findById(Long.valueOf(save1.getId()));
    System.out.println("customer " + byId);
  }
}

我在配置中指定了查询日志记录logging.level.org.hibernate.SQL=TRACE

spring.datasource.url=jdbc:mysql://localhost/demospring?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=*
spring.datasource.password=*
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
logging.level.org.hibernate.SQL=TRACE
log4j.logger.org.springframework.transaction=DEBUG
log4j.logger.org.springframework.orm.jpa=DEBUG

我在日志中看不到select查询,只有日志记录了持久化的实体:

2019-12-28 16:29:56.732  INFO 17623 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-12-28 16:29:57.331  INFO 17623 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 4.526 seconds (JVM running for 5.198)
2019-12-28 16:29:57.382 DEBUG 17623 --- [           main] org.hibernate.SQL                        : insert into customer (first_name, last_name) values (?, ?)
customer Optional[Customer[id=73, firstName='Jack3', lastName='Bauer']]
2019-12-28 16:30:03.455  INFO 17623 --- [       Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-12-28 16:30:03.457  INFO 17623 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-12-28 16:30:03.462  INFO 17623 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

这是主要课程:


@SpringBootApplication
public class DemoApplication
{
  private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);

  public static void main(String[] args)
  {
    SpringApplication.run(DemoApplication.class, args);
  }
  @Autowired
  BeanClass bc;
  @Bean
  public CommandLineRunner demo(CustomerRepository repository)
  {

    return (args) -> {
      bc.tran();
    };
  }
}

可以记录findById吗?

2 个答案:

答案 0 :(得分:8)

这是预料之中的:它不需要执行任何查询,因为您只是在同一事务中持久存储了实体:它位于第一级缓存中。

顺便说一句,那时它甚至还没有插入数据库。

如果您执行了一个事务来保存实体,并执行了另一个事务以ID查找它,那么您将看到正在执行的SQL查询。

答案 1 :(得分:0)

原因一级休眠缓存。

不会记录

findById,因为它处于同一事务中(该事务在进入方法tran()时启动)和相同的Hibernate会话。由于当前会话中已加载对象,因此不会执行findById的select查询。