gpt4 book ai didi

java - 不使用Spring获取EntityManager

转载 作者:行者123 更新时间:2023-11-30 05:08:25 25 4
gpt4 key购买 nike

我正在使用 hibernate,但没有使用 Spring,刚刚发现 hibernate-generic-dao 。这个概念看起来不错,但是当我运行它时,我得到一个 NPE,因为我没有调用 setEntityManager()。

如何在不使用 Spring 的情况下获取 EntityManager?

最佳答案

我有一些测试代码。它在 META-INF 目录中查找 persistence.xml 文件。

EntityManagerFactory emf=Persistence.createEntityManagerFactory("test-unit");
EntityManager em=emf.createEntityManager();

下面是一个 persistence.xml 示例,它使用连接到 postgresql 数据库的 hibernate 和两个实体类:

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/per\
sistence_1_0.xsd">
<persistence-unit name="test-unit" transaction-type="RESOURCE_LOCAL">
<class>com.example.package.Entity1</class>
<class>com.example.package.Entity2</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.driver_class"
value="org.postgresql.Driver"/>
<property name="hibernate.connection.username" value="login"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.url"
value="jdbc:postgresql://dbserver.internal:5432/dbname"/>
</properties>
</persistence-unit>
</persistence>

关于java - 不使用Spring获取EntityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4292759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com