简介

neo4j是一种图数据库,项目开发中可能会用到。

使用的版本:

  1. SpringBoot 2.5.5
  2. neo4j 4.3
  3. Java 11

Maven配置:

Maven只需要配置starter即可,但starter里只包含最新版本内容,不能兼容旧版本api(貌似)。所以写代码的时候要注意。

我觉得并不详细的官方文档

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-neo4j</artifactId>
  4. </dependency>

yaml配置:

这里配置的是bolt协议。
为什么使用bolt协议

  1. spring:
  2. neo4j:
  3. authentication:
  4. password: 123456
  5. username: neo4j
  6. uri: bolt://localhost:7687

使用ORM

完成配置之后,按照SpringBoot的常用层次搭建一个小demo。

项目结构如下:
image.png

实体层

注意:为了后续转换方便,最好把属性名和数据库里设置成一样的。

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. @Node(labels = {"Station"})
  5. public class Station implements Serializable {
  6. @Id
  7. @GeneratedValue
  8. private Long id; // 这个是系统生成的假id
  9. @Property(name = "name")
  10. private String name;
  11. @Property(name = "englishname")
  12. private String englishname;
  13. @Property(name = "stationid")
  14. private String stationid; // 真实使用的id
  15. @Relationship(type = "NEAR", direction = Relationship.Direction.OUTGOING)
  16. private Set<Station> nearStations = new HashSet<>();
  17. }

DAO

  1. @Repository
  2. public interface StationRespository extends Neo4jRepository<Station,Long> { // 类型和id对应
  3. @Query("MATCH (c:Station) WHERE c.stationid = $id RETURN c")
  4. Station findStationById(String id);
  5. @Query("MATCH (c:Station)-[r]->() WHERE r.name = $routeName RETURN c")
  6. List<Station> findStationsByName(String routeName);
  7. }

服务层

  1. @Service
  2. public class BusInfoServiceImpl implements BusInfoService{
  3. @Autowired
  4. StationRespository stationRespository;
  5. @Override
  6. public Station findStationById(String Id) {
  7. return stationRespository.findStationById(Id);
  8. }
  9. @Override
  10. public List<Station> findRouteByName(String routeName) {
  11. return stationRespository.findRouteByName(routeName);
  12. }
  13. }

控制层

  1. @RestController
  2. public class BusInfoController {
  3. @Autowired
  4. private BusInfoServiceImpl busInfoService;
  5. @GetMapping(path = "/StationById")
  6. public Station findStationById(
  7. @RequestParam(name = "id") String id
  8. ){
  9. return busInfoService.findStationById(id);
  10. }
  11. @GetMapping(path = "/RouteByName")
  12. public List<Station> findRouteByName(
  13. @RequestParam(name = "routeName") String routeName
  14. ){
  15. return busInfoService.findRouteByName(routeName);
  16. }
  17. }

使用Driver

ORM在有些方面不能很好满足我们的需求,可能有时会需要使用驱动连接数据库。

配置驱动:编写configuration

  1. // 因为要使用驱动开发,使用配置类装配Driver
  2. public class Neo4jConfig {
  3. @Value("${spring.neo4j.authentication.username}")
  4. private String username;
  5. @Value("${spring.neo4j.authentication.password}")
  6. private String password;
  7. @Value("${spring.neo4j.uri}")
  8. private String uri;
  9. @Bean
  10. public Driver neo4jDriver() {
  11. return GraphDatabase.driver(uri, AuthTokens.basic(username,password));
  12. }
  13. }

在开发中使用Driver的示例:

  1. try (Session session = neo4jDriver.session()) {
  2. String cypher = String.format("MATCH p=(s)-[r *.. {name:'%s'}]->(e) where '%s' in s.begins and '%s' in e.ends RETURN p", routeName, routeName, routeName);
  3. Result result = session.run(cypher);
  4. try {
  5. List<Record> records = result.list();
  6. Record record = null;
  7. if (records != null) {
  8. record = records.get(0);
  9. }
  10. Value value = record.get("p"); // 因为是return p
  11. Path path = value.asPath(); // 返回的是路径类型,故使用.asPath()
  12. // 得到node结果后,类型转换并加入line的station list
  13. for (Node node : path.nodes()) {
  14. Map<String, Object> map = node.asMap();
  15. String mapString = JSONObject.toJSONString(map);
  16. Station station = JSONObject.parseObject(mapString, Station.class); //json字符串直接转给java对象
  17. stations.add(station);
  18. }
  19. } catch (Exception e) {
  20. System.out.println("没有找到Record, name:" + routeName);
  21. }
  22. }