SpringMvc 使用 neo4j-java-driver操作neo4j

配置连接工具

package com.clinicalresearch.Rengine.connect;

import org.apache.log4j.Logger;
import org.clinicalresearch.utils.PropertiesUtil;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Created by  on 2019/12/11.
 * neo4j 连接工具
 */
@Component
public class Neo4jConfig {

    private static final Logger logger = Logger.getLogger(Neo4jConfig.class);

    private static String URL;

    private static String username;
    private static String password;

    private static final String CONF_NAME = "Neo4j.properties";

    static {
        PropertiesUtil.setPropertiesName(CONF_NAME);
        URL = PropertiesUtil.getValue("URL");
        username = PropertiesUtil.getValue("username");
        password = PropertiesUtil.getValue("password");

        logger.info("url:"+URL);
        logger.info("username:"+username);
        logger.info("password:"+password);
    }

    /**
     * 图数据库驱动模式
     *
     * @return
     */

    @Bean
    public  Driver neo4jDriver() {
        return GraphDatabase.driver(URL, AuthTokens.basic(username, password));
    }

}

neo4j 执行语句工具类

package com.clinicalresearch.Rengine.utils;

import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by on 2019/12/11.
 * 知识图谱 执行语句工具类
 */
@Component
public class Neo4jUtil {

    @Autowired
    private Driver neo4jDriver;

    public boolean isNeo4jOpen() {
        try (Session session = neo4jDriver.session()) {
            System.out.println("连接成功:" + session.isOpen());
            return session.isOpen();
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 执行语句
     * @param cypherSql
     * @return
     */
    public StatementResult excuteCypherSql(String cypherSql) {
        StatementResult result = null;

        if (isNeo4jOpen()){
            try (Session session = neo4jDriver.session()) {
                System.out.println(cypherSql);
                result = session.run(cypherSql);
                session.close();
            } catch (Exception e) {
                throw e;
            }
        }

        return result;
    }
}

接口中实现

@Override
public Object getKnowledgeGraph() throws Exception {

    String totalCountquery = "MATCH (n) RETURN count(distinct labels(n)) as count";
    StatementResult result = neo4jUtil.excuteCypherSql(totalCountquery);

    List records = result.list();
    System.out.println("result:"+records.size());


    return null;
}

你可能感兴趣的:(neo4j)