有没有办法在使用 Java Spring JPA 但没有 "persistence.xml" 文件的项目中获取 EntityManagerFactory?

Is there a way to get the EntityManagerFactory on a project that uses Java Spring JPA but doesn't have a "persistence.xml" file?

我想使用 EMF 在运行时对 String 构造查询。如果有人能告诉我如何做并举一个小例子,我将不胜感激。是的,我已经阅读了 Spring Data JPA Documentation about Specifications to do custom queries 但这不是我要找的。该项目没有定义持久性单元,而是在 spring 文件夹中有一个 application-config.xml 文件,该文件又引用文件 persistence-config.xml 并且里面有一个 bean是这样的:

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.drive_class}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
        <property name="maxActive" value="30" />
        <property name ="maxWait" value ="50000"/> 
        <property name = "testWhileIdle" value = "true" /> 
        <property name = "validationQuery" value = "select 1 from dual" /> 
        <property name = "testOnBorrow" value = "true" /> 
        <property name = "timeBetweenEvictionRunsMillis" value = "50000" />
  </bean>

这就是为什么建议使用从 Persistence Unit 的 Factory 创建的 EntityManager 的解决方案对我不起作用,因为这个项目不适用于那个。

如果我对你的问题的理解正确,你只是想知道如何使用支持 JPA 的小型 spring/spring-boot 项目进行练习。

我只是建议您下载 spring-boot 项目相关的源代码和示例。

如果你有时间: https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-jpa 可以作为参考。您可以下载该项目,阅读源代码并进行调试。您阅读的 JPA 文档中的代码足以 understanding/matching。

还有 https://www.baeldung.com/spring-boot-h2-database 本站有很多相关文章介绍spring/spring-boot相关攻略

希望对您有所帮助。

好吧,我不知道它是如何工作的,也不知道为什么会这样,但在互联网上的某个地方,我看到有人在使用它,并且从我这里开始工作。我假设该应用程序有自己的自动管理实体管理器工厂,您可以引用它并创建自己的实体管理器:

@PersistenceUnit
    private EntityManagerFactory emf;

在 class 的开头添加它(您进行声明的地方),它就可以工作...