【发布时间】:2015-07-20 17:56:07
【问题描述】:
我正在尝试创建一个 Spring Boot 应用程序,该应用程序使用 JPA 和 Postgresql 在程序启动时保留一个实体(如果它尚不存在)。该应用程序还使用 Spring Data Neo4J。当我在 run() 中对实体调用 save() 时,我可以看到没有创建任何实体。然而,当我使用来自 REST 控制器的相同代码时,实体就被创建了。如果我删除 Spring Data Neo4J 的所有部分,实体将在 run() 中创建。请问怎么了?
我的实体类:
@Entity
public class PersistentConfig {
// ------------------------
// PRIVATE FIELDS
// ------------------------
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
private Boolean hasBeenInitialised;
// ------------------------
// PUBLIC METHODS
// ------------------------
protected PersistentConfig() {}
public PersistentConfig(long id) {
this.id = id;
this.hasBeenInitialised= false;
}
public PersistentConfig(Boolean hasBeenInitialised) {
this.hasBeenInitialised = hasBeenInitialised;
}
// Getters and setters methods
// ...
Boolean getHasBeenInitialised() {
return hasBeenInitialised
}
void setHasBeenInitialised(Boolean hasBeenInitialised) {
this.hasBeenInitialised = hasBeenInitialised
}
@Override
public String toString() {
return "id: ${id}, hasBeenInitialised: ${hasBeenInitialised}"
}
}
存储库:
interface PersistentConfigRepository extends CrudRepository<PersistentConfig, Long> {
}
在主应用程序类中:
@Override
public void run(String... strings) throws Exception {
init()
}
public void init() {
if (persistentConfigRepository.count() == 0) {
try {
PersistentConfig pc = new PersistentConfig(false);
System.out.println("Created PersistentConfig: ${pc}");
def rc = persistentConfigRepository.save(pc);
System.out.println(rc)
}
catch (Exception ex) {
System.out.println("Error creating the PersistentConfig: " + ex.toString());
}
System.out.println("PersistentConfig succesfully created, repo count = ${persistentConfigRepository.count()}");
}
else {
System.out.println("PersistentConfig already exists");
}
}
static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
}
这是我在程序启动时得到的输出:
Created PersistentConfig: id: 0, hasBeenInitialised: false
id: 24, hasBeenInitialised: false
PersistentConfig succesfully created, repo count = 0
如果在控制器中使用init() 中的相同代码,则会创建并保留实体。 JPA 中的某些东西正在init() 中创建实体,因为id 正在递增(你可以看到我已经运行了几次程序......),但它只是没有进入数据库(依靠存储库)为零,当我检查桌子时,那里什么都没有。
编辑以显示相关日志,包括休眠日志语句:
Hibernate: select count(*) as col_0_0_ from persistent_config persistent0_
Created PersistentConfig: id: 0, hasBeenInitialised: false
Hibernate: select nextval ('hibernate_sequence')
id: 28, hasBeenInitialised: false
Hibernate: select count(*) as col_0_0_ from persistent_config persistent0_
PersistentConfig succesfully created, repo count = 0
编辑 2:当我删除所有 Spring Data Neo4J 代码时,我已经确定该代码有效。我需要对 DataSource bean 做些什么吗?
【问题讨论】:
-
你能说出你在控制台上看到
save之后的查询吗? -
我已将这些添加到问题中 - 我看不到有插入正在进行,只是一个选择。
-
代码是否需要包装在事务中,也许?
标签: hibernate jpa neo4j spring-boot spring-data-neo4j