我正在将Spring Data Neo4J 5.0.10与Spring Boot 2.0.5结合使用。我有以下2个节点实体,用户兴趣和关系实体用户兴趣。
@NodeEntity
public class User {
private Long id;
@Id
@GeneratedValue(strategy = UserIdStrategy.class)
@Convert(UuidStringConverter.class)
private UUID userId;
@Relationship(type = UserInterest.TYPE, direction = Relationship.OUTGOING)
private Set<UserInterest> interests = new HashSet<>();
... getters/setters
@NodeEntity
public class Interest {
private Long id;
@Id
@GeneratedValue(strategy = InterestIdStrategy.class)
private String interestId;
private String name;
... getters/setters
@RelationshipEntity(type = UserInterest.TYPE)
public class UserInterest {
public static final String TYPE = "INTERESTED_IN";
private Long id;
@StartNode
private User start;
@EndNode
private Interest end;
//private Long weight;
... getters/setters
这很好。我可以创建一个新用户并将该用户与userInterest关联。当我再次发送相同的详细信息时,节点和边不会重复。
当我在关系实体中启用权重属性时,即使权重属性值相同,似乎该关系也是重复的。
我记得读到,虽然属性相同,但是不应该创建另一个关系,对吗?
这是预期的行为,我该怎么做以防止重复关系?
答案 0 :(得分:3)
这是一个可行的解决方案。在我详细介绍之前:关键是您坚持不懈的事情。您应该以清晰的边界环境为目标,并且只对一个聚合感兴趣。我决定让用户成为事物的切入点。用户有兴趣,应该通过用户来添加和操纵兴趣。
OGM和Spring Data Neo4j负责保存用户传出的关系。
因此,主要要点是:不要自己保存每个NodeEntity
。以隐式方式保存实体之间的关联,即:仅保存父对象。您可以通过会话本身或通过存储库来完成此操作。请注意,您不需要每个实体的存储库。
由于您未共享自定义策略,因此我将其省略。我依靠生成的ID。如果我的示例无法采用您的策略,也许这是在哪里寻找错误的好提示。
我们感兴趣:
@NodeEntity
public class Interest {
@Id
@GeneratedValue
private Long id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
和用户的兴趣:
@RelationshipEntity(type = UserInterest.TYPE)
public class UserInterest {
public static final String TYPE = "INTERESTED_IN";
private Long id;
@StartNode
private User start;
@EndNode
private Interest end;
private Long weight;
public void setStart(User start) {
this.start = start;
}
public Interest getEnd() {
return end;
}
public void setEnd(Interest end) {
this.end = end;
}
public void setWeight(Long weight) {
this.weight = weight;
}
}
最后是用户:
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
@Relationship(type = UserInterest.TYPE, direction = Relationship.OUTGOING)
private Set<UserInterest> interests = new HashSet<>();
public void setName(String name) {
this.name = name;
}
public Interest setInterest(String interstName, long weight) {
final UserInterest userInterest = this.interests.stream()
.filter(i -> interstName.equalsIgnoreCase(i.getEnd().getName()))
.findFirst()
.orElseGet(() -> {
// Create a new interest for the user
Interest interest = new Interest();
interest.setName(interstName);
// add it here to the interests of this user
UserInterest newUserInterest = new UserInterest();
newUserInterest.setStart(this);
newUserInterest.setEnd(interest);
this.interests.add(newUserInterest);
return newUserInterest;
});
userInterest.setWeight(weight);
return userInterest.getEnd();
}
}
请参见setInterest
。这是使用User
作为聚合根访问所有事物的一种方法。此处:兴趣。如果存在,只需修改权重,否则创建一个新的权重,包括UserInterest
,将其添加到用户的兴趣中,最后设置权重,然后将其返回以供进一步使用。
然后,我声明一个一个存储库,仅供用户使用:
public interface UserRepository extends Neo4jRepository<User, Long> {
Optional<User> findByName(String name);
}
现在是应用程序:
@SpringBootApplication
public class SorelationshipsApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SorelationshipsApplication.class, args);
}
private final UserRepository userRepository;
private final SessionFactory sessionFactory;
public SorelationshipsApplication(UserRepository userRepository, SessionFactory sessionFactory) {
this.userRepository = userRepository;
this.sessionFactory = sessionFactory;
}
@Override
public void run(String... args) throws Exception {
Optional<User> optionalUser = this.userRepository
.findByName("Michael");
User user;
ThreadLocalRandom random = ThreadLocalRandom.current();
if(optionalUser.isPresent()) {
// Redefine interests and add a new one
user = optionalUser.get();
user.setInterest("Family", random.nextLong(100));
user.setInterest("Bikes", random.nextLong(100));
user.setInterest("Music", random.nextLong(100));
} else {
user = new User();
user.setName("Michael");
user.setInterest("Bikes", random.nextLong(100));
user.setInterest("Music", random.nextLong(100));
}
userRepository.save(user);
// As an alternative, this works as well...
// sessionFactory.openSession().save(user);
}
}
这只是针对我的本地Neo4j实例运行的命令行示例,但我认为它足以说明一切。
我检查用户是否存在。如果没有,请创建它并添加一些兴趣。在下一轮中,修改现有兴趣并创建一个新兴趣。任何进一步的运行只会改变现有的利益。
查看结果:
增加奖励:如果您使用的是Java 11,请参见ifPresentOrElse
上的Optional
。处理Optional的更多惯用方式。
userRepository.findByName("Michael").ifPresentOrElse(existingUser -> {
existingUser.setInterest("Family", random.nextLong(100));
existingUser.setInterest("Bikes", random.nextLong(100));
existingUser.setInterest("Music", random.nextLong(100));
userRepository.save(existingUser);
}, () -> {
User user = new User();
user.setName("Michael");
user.setInterest("Bikes", random.nextLong(100));
user.setInterest("Music", random.nextLong(100));
userRepository.save(user);
});
我希望有帮助。
编辑:这是我的依赖项:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sorelationships</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sorelationships</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>