我有一个使用Spring-Data-Neo4j的Spring-Boot项目,我无法弄清楚如何使用我的服务类映射我的关系。
我建立的API是以权力系列游戏为主题的。 你可以建造Kinggdoms和城堡(到目前为止),每个王国都可以拥有许多城堡,但每个城堡都允许有一个王国。
项目在GitHub上,请务必检查Dev分支以查找最新代码: https://github.com/darwin757/IceAndFire
问题:
我有我的王国Pojo,我添加了一个关系,它有一个城堡列表:
package com.example.Westeros.Kingdoms;
import java.util.ArrayList;
import java.util.List;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import com.example.Westeros.Castles.Castle;
@NodeEntity
public class Kingdom {
@GraphId private Long id;
private String name;
@Relationship(type = "Has a")
private List<Castle> castles = new ArrayList<Castle>();
public Kingdom() {}
public Kingdom(String name) {
super();
this.name = name;
}
//GETERS AND SETTERS FOR NAME
public List<Castle> getCastles() {
return castles;
}
public void addCastle(Castle castle) {
this.castles.add(castle);
}
}
我对Castle做了同样的事情:
package com.example.Westeros.Castles;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import com.example.Westeros.Kingdoms.Kingdom;
@NodeEntity
public class Castle {
@GraphId
private Long id;
private String name;
@Relationship(type = "belongs to")
private Kingdom kingdom;
public Castle() {}
public Castle(String name) {
super();
this.name = name;
}
//GETTERS AND SETTERS FOR NAME
}
现在我必须在服务中写什么才能将王国及其相关的城堡添加到数据库中?
到目前为止,我有这种错误的方法:
//FIXME I'M WRONG
public void addCastleToKingdom(String kingdomName,String castleName) {
Castle castle = new Castle(castleName);
castleRepository.save(castle);
getKingdom(kingdomName).addCastle(castle);
我想要一个能通过此测试的方法
@Test
public void addCastleToKingdomTest() {
kingdomService.addKingdom(theNorth);
kingdomService.addCastleToKingdom("The North", "Winterfell");
kingdomService.addCastleToKingdom("The North", "The Dreadfort");
kingdomService.addCastleToKingdom("The North", "White Harbor");
Assert.assertEquals("Winterfell", kingdomService.getKingdomsCastles("The North").get(0).getName());
Assert.assertEquals("The Dreadfort", kingdomService.getKingdomsCastles("The North").get(1).getName());
Assert.assertEquals("White Harbor", kingdomService.getKingdomsCastles("The North").get(2).getName());
}
答案 0 :(得分:1)
feature.properties.id
为王国增添了一座城堡,但并没有坚持修改。
这解决了问题:
addCastleToKingdomTest
甚至更好,因为对象图由SDN传递持久化:
public void addCastleToKingdom(String kingdomName,String castleName) {
Castle castle = new Castle(castleName);
castleRepository.save(castle);
Kingdom kingdom = getKingdom(kingdomName);
kingdom.addCastle(castle);
kingdomRepository.save(kingdom);
}