关于"如何在Neo4j"中动态添加标签的问题。有没有办法动态更改实体类型?
举个例子:
@NodeEntity
public class User {
@Properties(prefix = "custom")
private Map userProperties;
}
我从https://neo4j.com/blog/spring-data-neo4j-5-0-release/看到我可以创建动态属性。我也可以在运行时使用动态类型吗?我想改变用户"输入"消费者" /"管理员" /"制片人"需要时动态。实体类型并非详尽无遗。
提前致谢! :)
答案 0 :(得分:1)
@Labels
除了类和接口中的主要类型之外,还存储/管理Set<String>
注释。
答案 1 :(得分:0)
@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());
}
}
尽管这很简洁,但在更深层的嵌套类场景中,我会尽力而为。另外,如果您想以多态方式使用存储库,请按照我的意愿重新声明派生的finder方法。
我也有专用的存储库。
如果这个问题仍然与您有关,请告诉我是否也对您有用。您将在这里找到整个项目: