Spring boot集成neo4j和简单使用

关于spring boot集成neo4j和简单的使用

github:https://github.com/whl6785968/Neo4jDemo

[pom.xml] 

这里我使用neo4为5.2.2.RELEASE,neo4j sdn默认使用bolt连接方式,如果想使用http或embedded方式,需要添加依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sandalen</groupId>
    <artifactId>sbneo4j</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sbneo4j</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring.framework.version>5.2.1.RELEASE</spring.framework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-http-driver</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

[config.java]

在config里加载配置、返回sessionFactory以能够使用repository、开启事务

package com.sandalen.sbneo4j.config;

import org.neo4j.ogm.config.ClasspathConfigurationSource;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableNeo4jRepositories(basePackages = "com.sandalen.sbneo4j.repository")
@EnableTransactionManagement
public class Neo4jConfig {

    @Bean
    public SessionFactory sessionFactory(){
        return new SessionFactory(configuration(),"com.sandalen.sbneo4j.bean");
    }

    @Bean
    public org.neo4j.ogm.config.Configuration configuration(){
        ClasspathConfigurationSource source = new ClasspathConfigurationSource("ogm.properties");
        org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder(source).build();
        return configuration;
    }

    @Bean
    public Neo4jTransactionManager transactionManager(){
        return new Neo4jTransactionManager(sessionFactory());
    }
}

其中的[ogm.properties]为以下内容

URI=bolt://localhost:7687
username=neo4j
password=yourpassword

[xxxAplication.java]

开启实体扫描

@SpringBootApplication
@EntityScan(basePackages = "com.sandalen.sbneo4j.bean")
public class Sbneo4jApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sbneo4jApplication.class, args);
    }

}

[PersonRepository.java]

PersonRepository里有需要已经定义好的方法,直接使用即可,但是如下Person findByName(String name);为自定义方法,自定方法格式为 "findByxxx"(xxx可以为Person中的属性,也可以为如下表的格式)

@Repository
public interface PersonRepository extends Neo4jRepository<Person,Long> {
    Person findByName(String name);
}
KeywordSampleCypher snippet

After

findByLaunchDateAfter(Date date)

n.launchDate > date

Before

findByLaunchDateBefore(Date date)

n.launchDate < date

Containing (String)

findByNameContaining(String namePart)

n.name CONTAINS namePart

Containing(Collection)

findByEmailAddressesContains(Collection<String> addresses)

findByEmailAddressesContains(String address)

ANY(collectionFields IN [addresses] WHERE collectionFields in n.emailAddresses)

ANY(collectionFields IN address WHERE collectionFields in n.emailAddresses)

In

findByNameIn(Iterable<String> names)

n.name IN names

Between

findByScoreBetween(double min, double max)
findByScoreBetween(Range<Double> range)

n.score >= min AND n.score <= max
Depending on the Range definition n.score >= min AND n.score <= max or n.score > min AND n.score < max

StartingWith

findByNameStartingWith(String nameStart)

n.name STARTS WITH nameStart

EndingWith

findByNameEndingWith(String nameEnd)

n.name ENDS WITH nameEnd

Exists

findByNameExists()

EXISTS(n.name)

True

findByActivatedIsTrue()

n.activated = true

False

findByActivatedIsFalse()

NOT(n.activated = true)

Is

findByNameIs(String name)

n.name = name

NotNull

findByNameNotNull()

NOT(n.name IS NULL)

Null

findByNameNull()

n.name IS NULL

GreaterThan

findByScoreGreaterThan(double score)

n.score > score

GreaterThanEqual

findByScoreGreaterThanEqual(double score)

n.score >= score

LessThan

findByScoreLessThan(double score)

n.score < score

LessThanEqual

findByScoreLessThanEqual(double score)

n.score <= score

Like

findByNameLike(String name)

n.name =~ name

NotLike

findByNameNotLike(String name)

NOT(n.name =~ name)

Near

findByLocationNear(Distance distance, Point point)

distance( point(n),point({latitude:lat, longitude:lon}) ) < distance

Regex

findByNameRegex(String regex)

n.name =~ regex

And

findByNameAndDescription(String name, String description)

n.name = name AND n.description = description

Or

findByNameOrDescription(String name, String description)

n.name = name OR n.description = description (Cannot be used to OR nested properties)

[Person.java]

package com.sandalen.sbneo4j.bean;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.typeconversion.DateLong;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@NodeEntity
public class Person {
    @Id
    @GeneratedValue
    private Long id;


    private String name;
    private String sex;

    @DateLong
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date create;

    @Relationship(type = "朋友" ,direction = Relationship.OUTGOING)
    @JsonIgnore
    private Set<Person> friends = new HashSet<>();

    public void addFriends(Person person){
        friends.add(person);
    }

    @Relationship(type = "评分",direction = Relationship.OUTGOING)
    private Set<Rating> ratings = new HashSet<>();

    public Rating rating(Movie movie,int stars,String comment){
        Rating rating = new Rating(this,movie,comment,stars);
        ratings.add(rating);
        return rating;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getCreate() {
        return create;
    }

    public void setCreate(Date create) {
        this.create = create;
    }

    public Set<Person> getFriends() {
        return friends;
    }

    public void setFriends(Set<Person> friends) {
        this.friends = friends;
    }

    public Set<Rating> getRatings() {
        return ratings;
    }

    public void setRatings(Set<Rating> ratings) {
        this.ratings = ratings;
    }
}

下表为常用注解

类型注解意义作用域备注
基本注解@NodeEntity节点实体 
 @Id图标识属性必须使用长整型
 @Property属性属性 
 @Relationship关系属性 
 @Transient临时字段属性不参与持久化
 @RelationshipEntity关系实体 
 @StartNode开始节点属性 
 @EndNode结束节点属性 
类型转换@Convert类型转换属性 
 @DateLong日期长整型属性 
 @DateString日期字符串属性 
 @EnumString枚举字符串属性 
 @NumberString数字字符串属性 

[添加节点]

  public void addperson(){
        Person person = new Person();
        person.setCreate(new Date());
        person.setName("张莎");
        person.setSex("女");

        Person person2 = new Person();
        person2.setCreate(new Date());
        person2.setName("余琦");
        person2.setSex("女");
        
        //在创建节点的时候添加关系
        person.addFriends(person2);

        personRepository.save(person);
        personRepository.save(person2);

    }

  //创建新节点和已有节点的关系,即先查出来已有节点,再和新节点建立关系再存储
 public void addMovie(){
        Movie movie = new Movie();
        movie.setName("绣春刀");
        Person pers = personRepository.findByName("余琦");
        Rating rating = pers.rating(movie, 10, "好看");
        rating.setCreate(new Date());
        movie.addRating(rating);

        movieRepository.save(movie);
        
    }

结果如下,我也不晓得为那个电影节点的name没有显示到节点上 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值