tro*_*oig 2 java neo4j cypher spring-data spring-data-neo4j
我有一个简单的图形模型:1 User有N SocialUser。
我想知道当我删除实体时是否有任何方法spring-data-neo4j可以自动删除所有引用的内容。SocialUserUser
这是我到目前为止所得到的:
领域:
@NodeEntity
public class User implements IdentifiableEntity<String> {
@GraphId
private Long nodeId;
// ...
@RelatedTo(type = "HAS", direction = Direction.OUTGOING)
Set<SocialUser> socialUsers = new HashSet<>();
}
@NodeEntity
public class SocialUser implements BasicNodeEntity {
@GraphId
private Long nodeId;
//...
@RelatedTo(type = "HAS", direction = Direction.INCOMING)
User user;
}
Run Code Online (Sandbox Code Playgroud)
数据:

我尝试过的:
在这两种情况下,仅User删除:

目前,我已将两个实体的删除封装在服务@Transactional的方法中User。像这样的东西:
@Autowired
Neo4jOperations template;
@Transactional
public void delete(String userId) throws Exception {
User user = get(userId);
if (user == null) throw new ResourceNotFoundException("user not found");
Set<SocialUser> socialUsers = template.fetch(user.getSocialUsers());
for (SocialUser socialUser : socialUsers) template.delete(socialUser);
userRepository.delete(user);
}
Run Code Online (Sandbox Code Playgroud)
但我认为这可能不是实现这一目标的最佳方式。另外我认为直接执行Cypher语句来删除所有引用的节点可能会更好。
任何人都可以建议我如何处理这个问题?任何帮助将不胜感激。谢谢!
我知道已经有一段时间了,但是在使用SDNand一段时间之后neo4j,似乎完成此操作的最佳方法是使用查询Cypher。
MATCH (user:User{id:'userId'})-[has:HAS]->(socialUser:SocialUser)
DELETE user, has, socialUser
Run Code Online (Sandbox Code Playgroud)
通过SDN,我们可以利用存储库:
@Repository
public interface UserRepository extends Neo4jRepository<User> {
@Query("MATCH (user:User{id:{id}})-[has:HAS]->(socialUser:SocialUser) DELETE user, has, socialUser")
void delete(String id);
}
Run Code Online (Sandbox Code Playgroud)
希望它能帮助其他人
| 归档时间: |
|
| 查看次数: |
1685 次 |
| 最近记录: |