2019-01-18 · Develop

Spring Boot 集成 Neo4j 图数据库

什么是 Neo4j

Neo4j 是一个高性能的, NOSQL 图形数据库,它将结构化数据存储在网络上而不是表中。它是一个嵌入式的、基于磁盘的、具备完全的事务特性的 Java 持久化引擎,但是它将结构化数据存储在网络(从数学角度叫做图)上而不是表中。Neo4j 也可以被看作是一个高性能的图引擎,该引擎具有成熟数据库的所有特性。程序员工作在一个面向对象的、灵活的网络结构下而不是严格、静态的表中——但是他们可以享受到具备完全的事务特性、企业级的数据库的所有好处。
简单地说,我们可以说图数据库主要用于存储更多的连接数据。

安装

  1. 首先需要安装 jdk

  2. 添加 yum 源文件/etc/yum.repos.d/neo4j.repo

[neo4j]
name=Neo4j Yum Repo
baseurl=http://yum.neo4j.org/stable
enabled=1
gpgcheck=0
  1. 进行安装
yum install -y neo4j
  1. 修改最大打开文件限制,在文件/etc/security/limits.conf添加如下的信息
*               soft     nofile          65535
*               hard     nofile          65535
  1. 修改监听地址,在文件/etc/neo4j/neo4j.conf中取消掉下面配置的注释
dbms.connectors.default_listen_address=0.0.0.0
  1. 开发防火墙端口
firewall-cmd --permanent --zone=public --add-port=7474/tcp
firewall-cmd --reload
  1. 验证

访问如下的地址 http://127.0.0.1:7474

Spring Boot 集成

搜先映入依赖

<?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 http://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.1.2.RELEASE</version>
		<relativePath/>
	</parent>
	<groupId>com.example</groupId>
	<artifactId>neo4j</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>neo4j</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-neo4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

下面模拟一个场景:一部电影(Movie)中有多个角色(Role),每个角色由一名演员(Actor)来出演。建立如下的实体:

@NodeEntity @Getter @Setter public class Movie {
    @Id @GeneratedValue Long id;
    String title;
    String year;

    @Relationship(type="角色", direction = Relationship.OUTGOING)
    List<Role> roles = new ArrayList<>();

    public Role addRole(Actor actor, String name){
        Role role = new Role(actor,this, name);
        this.roles.add(role);
        return role;
    }
}
@NodeEntity @Getter @Setter
public class Actor {
    @Id @GeneratedValue Long id;
    private String name;
    private int born;
}
@RelationshipEntity(type = "角色") 
@Getter @Setter @NoArgsConstructor
public class Role {
    @Id @GeneratedValue Long id; String name;
    @StartNode Movie movie;
    @EndNode Actor actor;
    public Role(Actor actor, Movie movie, String name) {
        this.actor = actor;
        this.movie = movie;
        this.name = name;
    }
}

其中注解 @Relationship 表示 List 是一个关系集合,注解 @RelationshipEntity 表示实体是一个关系对象,注解 @StartNode@EndNode 分别表示关系的起点和终点。

然后创建两个 Repository 就可以使用了

@Repository
public interface ActorRepository extends Neo4jRepository<Actor, Long> {}
@Repository
public interface MovieRepository extends Neo4jRepository<Movie, Long> {
    Movie findByTitle(@Param("title") String title);
}

在配置文件 application.properties 中添加如下的信息

spring.data.neo4j.uri=bolt://192.168.19.124:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=neo4j

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class Neo4jTest {

    @Autowired
    MovieRepository movieRepository;
    @Autowired
    ActorRepository actorRepository;

    @Before
    public void initData() {
        movieRepository.deleteAll();
        actorRepository.deleteAll();

        Movie movie = new Movie();
        movie.setTitle("战狼");
        movie.setYear("2015");

        Actor wj = new Actor();
        wj.setBorn(1974);
        wj.setName("吴京");
        movie.addRole(wj, "冷峰");

        Actor yn = new Actor();
        yn.setBorn(1976);
        yn.setName("余男");
        movie.addRole(yn, "龙小云");

        movieRepository.save(movie);
        Assert.notNull(movie.getId(), "create error");
    }

    @Test
    public void get() {
        Movie movie = movieRepository.findByTitle("战狼");
        Assert.notNull(movie, "find error");
        log.info("===movie=== movie:{}, {}", movie.getTitle(), movie.getYear());
        for (Role role : movie.getRoles()) {
            log.info("====== actor:{}, role:{}", role.getActor().getName(), role.getName());
        }
    }
}

一运行就报如下的错误,查看错误信息可以知道,默认用户(neo4j)和默认密码(neo4j)需要修改才可以使用,然后再网页 http://127.0.0.1:7474 进行密码修改。

org.neo4j.driver.v1.exceptions.ClientException: Read operations are not allowed for user 'neo4j' with CREDENTIALS_EXPIRED.

The credentials you provided were valid, but must be changed before you can use this instance. If this is the first time you are using Neo4j, this is to ensure you are not using the default credentials in production. If you are not using default credentials, you are getting this message because an administrator requires a password change.
Changing your password is easy to do via the Neo4j Browser.
If you are connecting via a shell or programmatically via a driver, just issue a `CALL dbms.changePassword('new password')` statement in the current session, and then restart your driver with the new password configured.

修改完密码再重写运行,到网页中可以看到如下图的信息

neo4j-data

除了上面的连接方式外,还可以使用将 neo4j 进行嵌入式开发,需要修改的是依赖和配置:

在前面的基础上添加如下的依赖

<!-- Only add if you're using the Embedded driver -->
<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j-ogm-embedded-driver</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <!-- 嵌入式开发需要的jar包 -->
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>3.3.4</version>
</dependency>

将配置全部修改为如下

spring.data.neo4j.uri=file:///C:/Users/Administrator/Desktop/neo4j.db

参考文档
centos7 下Neo4j 安装配置备份
Spring Data Neo4j - Reference Documentation
Neo4j-OGM - An Object Graph Mapping Library for Neo4j v3.1