@EnableJpaAuditing和LocalSessionFactoryBean

时间:2018-11-15 10:46:23

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

将纯Spring v4应用程序迁移到Spring Boot 2.1之后,我在审核方面遇到了一些问题。

出于演示目的,我创建了一个小演示应用程序,其设置基本上如下所示:

@SpringBootApplication
public class HibernateWithJpaApplication {
    public static void main(String[] args) {
        SpringApplication.run(HibernateWithJpaApplication.class, args);
    }
}

@EnableJpaAuditing
@Configuration
@EnableJpaRepositories(basePackages = "com.github.hibernatewithjpa.repository", entityManagerFactoryRef = "sessionFactory")
@EnableTransactionManagement
public class ApplicationConfiguration {
    @Bean
    public LocalSessionFactoryBean sessionFactory(ConfigurableListableBeanFactory beanFactory, DataSource dataSource) {
        Properties properties = new Properties();
        properties.setProperty(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");

        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(dataSource);
        localSessionFactoryBean.setPackagesToScan("com.github.hibernatewithjpa.domain");
        localSessionFactoryBean.setHibernateProperties(properties);

        return localSessionFactoryBean;
    }
}

我还有一个非常简单的存储库和实体。

public interface ClientRepository extends PagingAndSortingRepository<Client, Integer> {
}

@Data
@Entity
@Table(name = "client")
@EntityListeners(AuditingEntityListener.class)
public class Client {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String name;

    @CreatedDate
    private Date created;
}

以下测试表明未应用审核:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HibernateWithJpaApplication.class)
public class ClientRepositoryTest {
    @Autowired
    private ClientRepository clientRepository;

    @Test
    public void test() {
        Client client = new Client();
        client.setName("df");

        this.clientRepository.save(client);
        client = this.clientRepository.findById(client.getId()).get();

        assertThat(client.getCreated()).isNotNull();
    }
}

该应用程序同时使用JPA和本机Hibernate查询。根据{{​​3}},使用LocalSessionFactoryBean应该是我们设置的正确方法。因此,LocalContainerEntityManagerFactoryBean并不是真正的选择。

调试时,我看到AnnotationBeanConfigurerAspect无法配置AuditingEntityListener bean,因为BeanConfigurerSupport错过了ConfigurableListableBeanFactory。因此未设置AuditingEntityListener的处理程序,因此不应用审核。

我现在想知道我做错了什么,或者这是Spring框架还是Spring Boot问题。

非常感谢您的帮助!

0 个答案:

没有答案