我對Spring JPA和ObjectDB數據庫的合作是一個新手,但是我遇到了一個我無法解決的問題。JPA,Spring和ObjectDB沒有更新
我有一個應用程序編寫的上述技術,它的工作正常,它堅持新的實體等(因此我認爲沒有問題的配置豆),除了更新甚至最簡單的關係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
頁面或TR裏在球隊所有球員y以相同的方式添加其他玩家,小隊總是空的 - 沒有任何東西持續存在於數據庫中。團隊對象,也不是玩家對象。我做錯了什麼?
任何幫助,將不勝感激。謝謝。
編輯:這裏是我的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>
附:絕對路徑"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" />
沒有徹底地讀你的代碼,這可能是原因:'cascade = CascadeType.PERSIST' - 你只是級聯持久。 – Thomas