springboot3整合高版本spring data neo4j

本博客适用于springboo data neo4j 7.2.6版本,详情阅读官网https://docs.spring.io/spring-data/neo4j/reference/7.2/introduction-and-preface/index.html,中文网只更新到了6版本

entity->node entity->relation

@Node("Movie")  // 取代了老版本的nodeentity,他表示的就是label
public class MovieEntity {

    @Id  // id标识没什么好说的,官方也提供了自动生成@GeneratedValue
    private final String title;

    @Property("tagline") // 代表一个label的属性
    private final String description;

    @Relationship(type = "ACTED_IN", direction = Direction.INCOMING) // 关系的创建直接在entity里即可,本样例中就是(MovieEntity)-[ACTED_IN]->(Roles)。向后阅读,这里是一个复合关系吗,用到了@RelationshipProperties
    private List<Roles> actorsAndRoles;

    @Relationship(type = "DIRECTED", direction = Direction.INCOMING) // 本样例是(MovieEntity)-[DIRECTED]->(PersonEntity)
    private List<PersonEntity> directors = new ArrayList<>();

    public MovieEntity(String title, String description) {  // 需要构造函数
        this.title = title;
        this.description = description;
    }

    // Getters omitted for brevity
}

一些映射注解

    @Node:表示类对数据库的映射
    @Id:
    @GeneratedValue:与 @Id一起应用,以指定应如何生成唯一标识符
    @Property:类属性对node属性的映射
    @Relationship:类属性对relation的映射,这个用在类内,指明(node)-[relation]->(node)
    @RelationshipProperties:类对relation的映射,这个用在类外,指明relation具体有什么属性  
    @TargetNode:用于 @RelationshipProperties注解的类的字段,以从另一端的角度标记该关系的目标

@Relationship:type/value为允许配置关系的类型,direction指定了方向,默认为OUTGOING

@RelationshipProperties使用案例:

@RelationshipProperties
public class Roles {

    @RelationshipId
    private Long id;

    private final List<String> roles;

    @TargetNode
    private final PersonEntity person;

    public Roles(PersonEntity person, List<String> roles) {
        this.person = person;
        this.roles = roles;
    }

    public List<String> getRoles() {
        return roles;
    }
}

示例(可选使用)基于neo4jclient的生成器

@Component
class MyIdGenerator implements IdGenerator<String> {
    private final Neo4jClient neo4jClient;
    public MyIdGenerator(Neo4jClient neo4jClient) {
        this.neo4jClient = neo4jClient;
    }
    @Override
    public String generateId(String primaryLabel, Object entity) {
        return neo4jClient.query("YOUR CYPHER QUERY FOR THE NEXT ID") //(1)
            .fetchAs(String.class).one().get();
    }
}
@Node("Movie")
public class MovieEntity {
    @Id @GeneratedValue(generatorRef = "myIdGenerator")
    private String id;
    private String name;
}

如何创建一个dao

@Repository
public interface IndustryDao extends Neo4jRepository<Industry,Long> {
}

 

posted @ 2024-06-04 20:02  天启A  阅读(778)  评论(0)    收藏  举报