如何注入EntityManagerFactory?

时间:2019-03-04 14:10:30

标签: spring-boot

this tutorial中,说

  

Spring Boot将Hibernate配置为默认的JPA提供程序,因此它是   除非我们不再需要定义entityManagerFactory bean   要自定义它。

,那么如何在类中自动将其布线?

1 个答案:

答案 0 :(得分:2)

我曾经用它做我的一个项目。请检查以下代码以供参考。

@Component 
public class XXXServiceImpl {


    private EntityManagerFactory emf;

    @Autowired
    private DataSource dataSource;

    private final String DropQuery = "DROP  table "+Schema_Name + ".";


    @Autowired
    public XXXServiceImpl(EntityManagerFactory emf) {
        Assert.notNull(emf, "EntityManagerFactory must not be null");
        this.emf = emf;
    }

    public void dropAllChildTables(String tableNamePrefix) {

        EntityManager entityManager = emf.createEntityManager();
        entityManager.getTransaction().begin();

        List<?> tables = entityManager.createNativeQuery(ListTableQry).setParameter("namePrefix", tableNamePrefix).getResultList();

        tables.forEach(tname -> {
            String query = DropQuery + "\"" + tname + "\"";
            entityManager.createNativeQuery(query).executeUpdate();
        });

        entityManager.getTransaction().commit();
        entityManager.close();
    }
}