Spring Boot中引入Neo4j圖形資料庫
阿新 • • 發佈:2019-01-14
建立節點(node),查詢節點,為了好的展示效果,對關係(relation)的處理後續再說。
1、Neo4j配置
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
application.properties
spring.data.neo4j.username=neo4j
spring. data.neo4j.password=123456
Neo4jConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
@Configuration
@EnableNeo4jRepositories(basePackages="com.test.demo.neo4j")
//上述配置如果不起作用,可以主啟動類配置@ComponentScan("com.test.demo.neo4j")
public class Neo4jConfig {
}
2、業務模擬
NeoPerson.java
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;
@NodeEntity(label = "Person")
public class NeoPerson {
/**
* Neo4j會分配ID
*/
@Id
@GeneratedValue
private Long id;
/**
* 屬性
*/
@Property(name = "name")
private String name;
@Property(name = "age")
private Long age;
@Property(name = "born")
private Long born;
get,set...
}
PersonRepository.java
@Repository
public interface PersonRepository extends CrudRepository<NeoPerson, Long> {
@Query("MATCH (n:Person) RETURN n ")
List<NeoPerson> getUserNodeList();
/**
* spring-data-neo4j 支援方法命名約定查詢 findBy{Coder的屬性名}
* @param name
* @return
*/
NeoPerson findByName(@Param("name") String name);
@Query("create (n:Person{name:{name},age:{age},born:{born}}) RETURN n ")
List<NeoPerson> addUserNode(@Param("name") String name, @Param("age")Long age,@Param("born") Long born);
}
Neo4jService.java
@Service
public class Neo4jService {
@Autowired
private PersonRepository personRepository;
public List<NeoPerson> addUser(NeoPerson userNode){
return personRepository.addUserNode(userNode.getName(),userNode.getAge(),userNode.getBorn());
}
public List<NeoPerson> findAllUser(){
return personRepository.getUserNodeList();
}
public NeoPerson findByName(String name) {
return personRepository.findByName(name);
}
}
Neo4jController.java
@RestController
@RequestMapping("/neo")
public class Neo4jController {
@Autowired
// 自動從spring容器中載入personService
private Neo4jService personService;
@RequestMapping("/findAllUser")
public List<NeoPerson> findAllUser() {
return this.personService.findAllUser();
}
@RequestMapping("/findone")
public NeoPerson findByName(String name) {
return this.personService.findByName(name);
}
@RequestMapping("/add")
public List<NeoPerson> addUsesr(NeoPerson user) {
return this.personService.addUser(user);
}
}
執行
1、增加使用者:瀏覽器中訪問http://cos6743:8081/neo/add?name=JavaNeo&age=33&born=1998
返回結果:[{“name”:“JavaNeo”,“age”:33,“born”:1998}]
2、檢視使用者:瀏覽器中訪問http://cos6743:8081/neo/findAllUser
返回結果:[{“born”:null,“name”:“Yang Tom”,“age”:35},{“born”:null,“name”:“Lilly Wski”,“age”:34},{“born”:1978,“name”:“Emil Eifrem”,“age”:null}]