有一个关于“如何动态地向Neo4j中的节点添加标签”的问题。有没有办法动态更改实体类型?
举个例子:
@NodeEntity
public class User {
@Properties(prefix = "custom")
private Map userProperties;
}
我从https://neo4j.com/blog/spring-data-neo4j-5-0-release/看到我可以创建动态属性。我也可以在运行时使用动态类型吗?我想在需要时动态地将“用户”类型更改为“消费者”/“管理员”/“生产者”。实体类型并非详尽无遗。
提前致谢! :)
在@Labels
上有一个Set<String>
注释,除了类和接口的主类型之外,它还存储/管理。
@Labels
机制很棒,对于许多用例来说,这是我所说的最佳解决方案。
如果你想从你的存储库中取出另一个类,那么确实需要做更多的工作。
我在音乐相关项目中这样做。我有Artist
(不抽象,完全可用于任何我不知道是否是乐队的乐队)和Band
和SoloArtist
从Artist延伸,附加标签:
@NodeEntity
public class Artist {}
@NodeEntity
public class Band extends Artist{}
我在自定义存储库扩展中知道的是:
interface ArtistRepository<T extends Artist> extends Repository<T, Long>, ArtistRepositoryExt {
Optional<T> findOneByName(String name);
// Specifying the relationships is necessary here because the generic queries won't recognize that
// Band has a relationship to country that _should_ be loaded with default depth of 1.
@Query("MATCH (n:Artist) WITH n MATCH p=(n)-[*0..1]-(m) RETURN p ORDER BY n.name")
List<T> findAllOrderedByName();
@Query("MATCH (n:Artist) WHERE id(n) = $id WITH n MATCH p=(n)-[*0..1]-(m) RETURN p")
Optional<T> findById(@Param("id") Long id);
<S extends T> S save(S artist);
}
interface ArtistRepositoryExt {
Band markAsBand(Artist artist);
SoloArtist markAsSoloArtist(Artist artist);
}
class ArtistRepositoryExtImpl implements ArtistRepositoryExt {
private static final String CYPHER_MARK_AS_BAND = String.format(
"MATCH (n) WHERE id(n) = $id\n" +
"OPTIONAL MATCH (n) - [f:BORN_IN] -> (:Country)\n" +
"REMOVE n:%s SET n:%s\n" +
"DELETE f",
SoloArtist.class.getSimpleName(),
Band.class.getSimpleName());
private static final String CYPHER_MARK_AS_SOLO_ARTIST = String.format(
"MATCH (n) WHERE id(n) = $id\n" +
"OPTIONAL MATCH (n) - [f:FOUNDED_IN] -> (:Country)\n" +
"REMOVE n:%s SET n:%s\n" +
"DELETE f",
Band.class.getSimpleName(),
SoloArtist.class.getSimpleName());
private final Session session;
public ArtistRepositoryExtImpl(Session session) {
this.session = session;
}
@Override
public Band markAsBand(Artist artist) {
session.query(CYPHER_MARK_AS_BAND, Map.of("id", artist.getId()));
// Needs to clear the mapping context at this point because this shared session
// will know the node only as class Artist in this transaction otherwise.
session.clear();
return session.load(Band.class, artist.getId());
}
@Override
public SoloArtist markAsSoloArtist(Artist artist) {
session.query(CYPHER_MARK_AS_SOLO_ARTIST, Map.of("id", artist.getId()));
// See above
session.clear();
return session.load(SoloArtist.class, artist.getId());
}
}
虽然这很好用,但我会在更深层次的嵌套类场景中获得努力的想法。此外,如果您想以多态方式使用存储库,那么您可以按照我的要求执行redeclare派生的finder方法。
我也保留了专用的存储库。
如果这个问题仍然与您有关,请告诉我是否也适合您。你会在这里找到整个项目: