我是 Spring JPA 与 ObjectDB 数据库合作的新手,但我遇到了一个我无法解决的问题。
我有一个使用上述技术编写的应用程序,它工作正常,它保留了新实体等(因此我认为配置 bean 没有问题),除了更新甚至最简单的OneToMany
/ManyToOne
关系。这些更新没有保存到数据库中,我不知道为什么。这是我的代码片段:
实体团队(1:N):
@Entity
public class Team implements Serializable {
...
List<Player> squad;
...
@OneToMany(mappedBy="team", cascade=CascadeType.PERSIST)
public List<Player> getSquad() {
return squad;
}
...
}
实体玩家 (N:1)
@Entity
public class Player implements Serializable {
...
private Team team;
...
@ManyToOne
public Team getTeam() {
return team;
}
...
}
这是来自控制器的片段,它同时使用了 DAO 对象和问题:
public ModelAndView addPlayer(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
Team t = teamDao.getTeamById(1); // retrieves an object with ID=1
Player p = playerDao.getPlayerById(1); // retrieves a player with ID=1
t.getSquad().add(p); // adds a player to the squad -> working fine but does not persist
System.out.println("Size of squad: " + t.getSquad().size()); // the player is there
...
return new ModelAndView("index.jsp", "team", t);
}
当我尝试在页面内列出球队中的所有球员index.jsp
或尝试以相同方式添加另一名球员时,球队总是空的 - 没有任何东西保存到数据库中。既不是团队对象,也不是玩家对象。我做错了什么?
任何帮助,将不胜感激。谢谢。
编辑:这是我的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="NewPU" transaction-type="RESOURCE_LOCAL">
<provider>com.objectdb.jpa.Provider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="C:/file.odb" />
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
PS绝对路径"C:/file.odb"
仅用于演示目的。
这是Spring配置:
<mvc:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="NewPU" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />