【发布时间】:2017-05-18 22:06:50
【问题描述】:
我一直在努力配置 Hibernate 并在 WildFly 上运行它。
这是我的代码:
META-INF/persistence.xml
<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/persistence_1_0.xsd">
<persistence-unit name="blog" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/blog?createDatabaseIfNotExist=true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="abc"/>
<property name="hibernate.connection.password" value="abc"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0"/>
</properties>
</persistence-unit>
pom.xml
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
用户:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@OneToMany(mappedBy = "user")
private Set<Post> posts;
}
当我加载我的主页时,没有创建数据库。
此外,我想保留一个用户。
@Stateless
public class UserRepositoryImpl implements UserRepository {
@PersistenceContext(unitName = "blog")
private EntityManager entityManager;
public void create(User user) {
this.entityManager.persist(user);
}
}
没有创建数据库并且实体管理器为空。我需要配置什么才能使其运行? 我正在使用 IntelliJ 进行测试。
【问题讨论】:
-
首先,当使用
JTA作为事务类型时,数据库连接细节不应该在persistence.xml文件中。它们应该在您的 WilfFly 的standalone.xml中。然后persistence.xml只是引用它。 -
我猜其他的东西从根本上被破坏了。我找不到一个很好的教程如何做到这一点。我暂时离开它。谢谢
-
问题可能出在您使用 UserRepositoryImpl 的方式上。如:您未在此处提供的代码。显然 JEE 容器没有被触发以实际注入 entityManager 实例并因此启动持久性上下文,我只能假设这意味着 USerRepositoryImpl 没有被初始化为正确的 EJB 实例。
标签: hibernate jpa jakarta-ee intellij-idea wildfly