Bootstrap

springboot使用neo4j

依赖

<dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-jdbc-driver</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-http-driver</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-kernel</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-api</artifactId>
            <version>3.1.8</version>
        </dependency>

neo4j任务管理器

import org.neo4j.driver.v1.*;
import org.neo4j.ogm.session.SessionFactory;
import org.neo4j.ogm.session.event.EventListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.data.neo4j.Neo4jProperties;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
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;
import org.springframework.util.StringUtils;

import java.util.List;

@Configuration
@EnableNeo4jRepositories(
        basePackages = "com.zsz.mapper.node",
        sessionFactoryRef = "neo4jSessionFactory",
        transactionManagerRef="neo4jTransaction"
)
@EntityScan(basePackages = "com.zsz.entity")
@EnableTransactionManagement
@EnableConfigurationProperties(Neo4jProperties.class)
public class Neo4jConfig {

    @Value("${spring.data.neo4j.username}")
    private String username;

    @Value("${spring.data.neo4j.password}")
    private String password;

    @Value("${spring.data.neo4j.uri}")
    private String uri;

    @Bean
    public org.neo4j.ogm.config.Configuration configuration(Neo4jProperties properties) {
        return properties.createConfiguration();
    }

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

    @Bean
    public Session getSession() {
        Driver driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password));
        Session session = driver.session();
        return session;
    }

    @Bean("neo4jSessionFactory")
    public SessionFactory sessionFactory(org.neo4j.ogm.config.Configuration configuration,
                                         ApplicationContext applicationContext,
                                         ObjectProvider<EventListener> eventListeners) {
        SessionFactory sessionFactory = new SessionFactory(configuration,
                getPackagesToScan(applicationContext));
        eventListeners.stream().forEach(sessionFactory::register);
        return sessionFactory;
    }

    @Bean("neo4jTransaction")
    public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory,
                                                      Neo4jProperties properties,
                                                      ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
        return customize(new Neo4jTransactionManager(sessionFactory),
                transactionManagerCustomizers.getIfAvailable());
    }

    private String[] getPackagesToScan(ApplicationContext applicationContext) {
        List<String> packages = EntityScanPackages.get(applicationContext).getPackageNames();
        if (packages.isEmpty() && AutoConfigurationPackages.has(applicationContext)) {
            packages = AutoConfigurationPackages.get(applicationContext);
        }
        return StringUtils.toStringArray(packages);
    }

    private Neo4jTransactionManager customize(Neo4jTransactionManager transactionManager,
                                              TransactionManagerCustomizers customizers) {
        if (customizers != null) {
            customizers.customize(transactionManager);
        }
        return transactionManager;
    }

neo4jUtils工具类

import com.alibaba.druid.util.StringUtils;
import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import org.neo4j.driver.v1.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Description: neo4j工具类
 * @Date: Created in 10:16 2019-06-25
 * @Author: daihui
 * @Modified By:
 */
@Component
public class Neo4jUtil {

    private Logger logger = LoggerFactory.getLogger(Neo4jUtil.class);

    private static final String NEO4J_NULL_TYPE = "NULL";

    private static final String NEO4J_NODE_TYPE = "NODE";

    private static final String NEO4J_PATH_TYPE = "PATH";

    private static final String NEO4J_LIST_TYPE = "LIST";

    private static final String NEO4J_MAP_TYPE = "MAP";

    private static final String NEO4J_RELATIONSHIP_TYPE = "RELATIONSHIP";

    private static final String SERIALVERSIONUID = "serialversionuid";

    private static final String INTEGER = "INTEGER";

    private static  final String LABELS ="labels";

    @Autowired
    private Driver neo4jDriver;

    /**
     * 执行Cypher
     *
     * @param cypher cypher语句
     * @return StatementResult
     *//**//**/
    public StatementResult executeCypher(String cypher) {
        StatementResult result;
        try (Session session = neo4jDriver.session()) {
            result = session.run(cypher);
        } catch (Exception e) {
            logger.error("执行Cypher出错:{}", e.toString());
            throw e;
        }
        return result;
    }
    public StatementResult run(String cypher, HashMap<String, Object> hashMap ) {
        StatementResult result;
        try (Session session = neo4jDriver.session()) {
            result = session.run(cypher,hashMap);
        } catch (Exception e) {
            logger.error("执行Cypher出错:{}", e.toString());
            throw e;
        }
        return result;
    }

    /**
     * 执行Cypher
     *
     * @param cyphers cypher语句
     * @return StatementResult
     *//**//**/
    public synchronized List<StatementResult> executeCypherList(List<String> cyphers) {
        List<StatementResult> statementResults = new ArrayList<>();
        try (Session session = neo4jDriver.session()) {
            for (String cypher : cyphers) {
                StatementResult result = session.run(cypher);
                statementResults.add(result);
            }
        } catch (Exception e) {
            logger.error("执行Cypher出错:{}", e.toString());
            throw e;
        }
        return statementResults;
    }
    /**
     * 获取节点类型为NODE的节点信息
     *
     * @param cypher cypher语句
     * @return List<HashMap < String, Object>>
     */
    public List<HashMap<String, Object>> getGraphNode(String cypher) {
        List<HashMap<String, Object>> nodes = new ArrayList<>();
        try {
            StatementResult result = this.executeCypher(cypher);
            if (result.hasNext()) {
                for (Record record : result.list()) {
                    HashMap<String, Object> rss = new HashMap<>(16);
                    for (Pair<String, Value> pair : record.fields()) {
                        String typeName = pair.value().type().name();
                        if (NEO4J_NODE_TYPE.equals(typeName)) {
                            Node node = pair.value().asNode();
                            String id = Long.toString(node.id());
                            rss.putAll(node.asMap());
                            rss.put("id", Long.parseLong(id));
                            rss.put("labelList",node.labels());
                        }
                    }
                    nodes.add(rss);
                }
            }

        } catch (Exception e) {
            logger.error("执行getGraphNode()出错:{}", e.toString());
            e.printStackTrace();
        }
        return nodes;
    }

    /**
     * 根据cypher获取节点信息
     *
     * @param cypher cypher语句
     * @return HashMap<String, Object>
     */
    public HashMap<String, Object> getEntityMap(String cypher) {
        HashMap<String, Object> resultMap = new HashMap<>(16);
        try {
            StatementResult result = executeCypher(cypher);
            if (result.hasNext()) {
                List<Record> records = result.list();
                for (Record recordItem : records) {
                    for (Value value : recordItem.values()) {
                        // 结果里面只要类型为节点的值
                        if (NEO4J_NODE_TYPE.equals(value.type().name())) {
                            Node noe4jNode = value.asNode();
                            Map<String, Object> map = noe4jNode.asMap();
                            for (Map.Entry<String, Object> entry : map.entrySet()) {
                                String key = entry.getKey();
                                if (resultMap.containsKey(key)) {
                                    String oldValue = resultMap.get(key).toString();
                                    String newValue = String.join(",", oldValue, String.valueOf(entry.getValue()));
                                    resultMap.replace(key, newValue);
                                } else {
                                    resultMap.put(key, entry.getValue());
                                }
                            }

                            resultMap.put("id",Long.toString(noe4jNode.id()));
                            resultMap.put("labelList", Collections.singletonList(noe4jNode.labels()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getEntityMaps()出错:{}", e.toString());
            throw e;
        }
        return resultMap;
    }


    /**
     * 根据cypher获取节点信息
     *
     * @param cypher cypher语句
     * @return List<HashMap < String, Object>>
     */
    public List<HashMap<String, Object>> getGraphNodes(String cypher) {
        List<HashMap<String, Object>> graphNodes = new ArrayList<>();

        try {
            StatementResult statementResult = this.executeCypher(cypher);
            if (statementResult.hasNext()) {
                List<Record> records = statementResult.list();
                for (Record record : records) {
                    for (Pair<String, Value> pair : record.fields()) {
                        HashMap<String, Object> rss = new HashMap<>(16);
                        if (NEO4J_NODE_TYPE.equals(pair.value().type().name())) {
                            Node neo4jNode = pair.value().asNode();
                            String id = Long.toString(neo4jNode.id());
                            for (Map.Entry<String, Object> entry : neo4jNode.asMap().entrySet()) {
                                rss.put(entry.getKey(), entry.getValue());
                            }
                            rss.put("id", id);
                            graphNodes.add(rss);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getGraphNodes()出错:{}", e.toString());
            throw e;
        }
        return graphNodes;
    }

    /**
     * 根据cypher获取图关系
     *
     * @param cypher cypher语句
     * @return List<HashMap < String, Object>>
     */
    public List<HashMap<String, Object>> getGraphRelationShip(String cypher) {
        List<HashMap<String, Object>> graphRelationShip = new ArrayList<>();
        try {
            StatementResult statementResult = this.executeCypher(cypher);
            while (statementResult.hasNext()) {
                for (Record record : statementResult.list()) {
                    for (Pair<String, Value> pair : record.fields()) {
                        HashMap<String, Object> rss = new HashMap<>(16);
                        if (NEO4J_RELATIONSHIP_TYPE.equals(pair.value().type().name())) {
                            Relationship relationship = pair.value().asRelationship();
                            String sourceId = Long.toString(relationship.startNodeId());
                            String targetId = Long.toString(relationship.endNodeId());
                            for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                if("randomId".equals(entry.getKey())){
                                    rss.put("id", entry.getValue());
                                }
                                rss.put(entry.getKey(), entry.getValue());
                            }
                            rss.put("labelList", Collections.singletonList(relationship.type()));
                            rss.put("source", sourceId);
                            rss.put("target", targetId);
                            graphRelationShip.add(rss);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getGraphRelationShip()出错:{}", e.toString());
            throw e;
        }
        return graphRelationShip;
    }

    /**
     * 获取图元素
     *
     * @param cypher cypher语句
     * @return List<HashMap < String, Object>>
     */
    public List<HashMap<String, Object>> getGraphItem(String cypher) {
        List<HashMap<String, Object>> ents = new ArrayList<>();
        List<String> nodeIds = new ArrayList<>();
        List<String> shipIds = new ArrayList<>();
        try {
            StatementResult result = this.executeCypher(cypher);
            if (result.hasNext()) {
                for (Record record : result.list()) {
                    HashMap<String, Object> rss = new HashMap<>(16);
                    for (Pair<String, Value> pair : record.fields()) {
                        String typeName = pair.value().type().name();
                        if (NEO4J_NODE_TYPE.equals(typeName)) {
                            Node noe4jNode = pair.value().asNode();
                            String id = Long.toString(noe4jNode.id());
                            if (!nodeIds.contains(id)) {
                                Map<String, Object> map = noe4jNode.asMap();
                                for (Map.Entry<String, Object> entry : map.entrySet()) {
                                    rss.put(entry.getKey(), entry.getValue());
                                }
                                rss.put("id", id);
                                nodeIds.add(id);
                            }
                        } else if (NEO4J_RELATIONSHIP_TYPE.equals(typeName)) {
                            Relationship relationship = pair.value().asRelationship();
                            String id = Long.toString(relationship.id());
                            if (!shipIds.contains(id)) {
                                String sourceId = Long.toString(relationship.startNodeId());
                                String targetId = Long.toString(relationship.endNodeId());
                                for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                    rss.put(entry.getKey(), entry.getValue());
                                }
                                rss.put("id", id);
                                rss.put("source", sourceId);
                                rss.put("target", targetId);
                                shipIds.add(id);
                            }
                        } else {
                            rss.put(pair.key(), pair.value());
                        }
                    }
                    ents.add(rss);
                }
            }
        } catch (Exception e) {
            logger.error("执行getGraphItem()出错:{}", e.toString());
            throw e;
        }
        return ents;
    }

    /**
     * 获取值类型的结果,如count,id
     *
     * @param cypher cypher语句
     * @return long
     */
    public long getGraphValue(String cypher) {
        long val = 0;
        try {
            StatementResult statementResult = this.executeCypher(cypher);
            if (statementResult.hasNext()) {
                for (Value value : statementResult.next().values()) {
                    val = value.asLong();
                }
            }
        } catch (Exception e) {
            logger.error("执行getGraphItem()出错:{}", e.toString());
            e.printStackTrace();
        }
        return val;
    }


    /**
     * 获取图谱节点和关系
     * 该方法待重构
     *
     * @param cypher cypher语句
     * @return HashMap<String, Object>
     */
    public HashMap<String, Object> getGraphNodeAndShip(String cypher) {
        HashMap<String, Object> nodeAndShip = new HashMap<>(16);
        try {
            StatementResult statementResult = this.executeCypher(cypher);
            if (statementResult.hasNext()) {
                List<HashMap<String, Object>> nodes = new ArrayList<>();
                List<HashMap<String, Object>> ships = new ArrayList<>();
                List<String> ids = new ArrayList<>();
                List<String> shipIds = new ArrayList<>();
                for (Record record : statementResult.list()) {
                    HashMap<String, Object> labelAndTypeMap = new HashMap<>();
                    for (Pair<String, Value> pair : record.fields()) {
                        //记录关系
                        HashMap<String, Object> recordShips = new HashMap<>(16);
                        //记录节点
                        HashMap<String, Object> rss = new HashMap<>(16);
                        String typeName = pair.value().type().name();
                        if (NEO4J_NULL_TYPE.equals(typeName)) {
                            continue;
                        }
                        else if (NEO4J_NODE_TYPE.equals(typeName)) {
                            Node neo4jNode = pair.value().asNode();
                            String id = Long.toString(neo4jNode.id());
                            if (!ids.contains(id)) {
                                for (Map.Entry<String, Object> entry : neo4jNode.asMap().entrySet()) {
                                    if("entityName".equals(entry.getKey())||"valueNum".equals(entry.getKey())){
                                        rss.put("name",entry.getValue());
                                    }
                                    rss.put(entry.getKey(), entry.getValue());
                                }
                                rss.put("id", id);
                                ids.add(id);
                                rss.put("labelList",neo4jNode.labels());
                                if (!rss.isEmpty()) {
                                    nodes.add(rss);
                                }
                            }
                        }
                        else if (NEO4J_RELATIONSHIP_TYPE.equals(typeName)) {
                            Relationship relationship = pair.value().asRelationship();
                            String id = Long.toString(relationship.id());
                            if (!shipIds.contains(id)) {
                                String sourceId = Long.toString(relationship.startNodeId());
                                String targetId = Long.toString(relationship.endNodeId());
                                for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                    if("randomId".equals(entry.getKey())){
                                        recordShips.put("id", entry.getValue());
                                    }
                                    recordShips.put(entry.getKey(), entry.getValue());
                                }
                                recordShips.put("source", sourceId);
                                recordShips.put("target", targetId);
                                recordShips.put("labelList",relationship.type());
                                shipIds.add(id);
                                if (!recordShips.isEmpty()) {
                                    ships.add(recordShips);
                                }
                            }
                        }
                        else if (NEO4J_PATH_TYPE.equals(typeName)) {
                            Path path = pair.value().asPath();
                            // start node
                            String startNodeId = Long.toString(path.start().id());
                            if (!ids.contains(startNodeId)) {
                                rss = new HashMap<>(16);
                                for (Map.Entry<String, Object> entry : path.start().asMap().entrySet()) {
                                    rss.put(entry.getKey(), entry.getValue());
                                }
                                rss.put("id", startNodeId);
                                rss.put("labelList", path.start().labels());
                                ids.add(startNodeId);
                                if (!rss.isEmpty()) {
                                    nodes.add(rss);
                                }
                            }
                            // end node
                            String endNodeId = Long.toString(path.end().id());
                            if (!ids.contains(endNodeId)) {
                                rss = new HashMap<>(16);
                                for (Map.Entry<String, Object> entry : path.end().asMap().entrySet()) {
                                    rss.put(entry.getKey(), entry.getValue());
                                }
                                rss.put("id", endNodeId);
                                rss.put("labelList", path.end().labels());
                                ids.add(endNodeId);
                                if (!rss.isEmpty()) {
                                    nodes.add(rss);
                                }
                            }
                            Iterator<Node> allNodesIterator = path.nodes().iterator();
                            while (allNodesIterator.hasNext()) {
                                Node node = allNodesIterator.next();
                                String id = Long.toString(node.id());
                                if (!ids.contains(id)) {
                                    rss = new HashMap<>();
                                    for (Map.Entry<String, Object> entry : node.asMap().entrySet()) {
                                        rss.put(entry.getKey(), entry.getValue());
                                    }
                                    rss.put("id", id);
                                    rss.put("labelList", node.labels());
                                    ids.add(id);
                                    if (!rss.isEmpty()) {
                                        nodes.add(rss);
                                    }
                                }
                            }
                            // relationship
                            Iterator<Relationship> relationshipIterator = path.relationships().iterator();
                            while (relationshipIterator.hasNext()) {
                                Relationship relationship = relationshipIterator.next();
                                String id = Long.toString(relationship.id());
                                if (!shipIds.contains(id)) {
                                    recordShips = new HashMap<>(16);
                                    String sourceId = Long.toString(relationship.startNodeId());
                                    String targetId = Long.toString(relationship.endNodeId());
                                    String rela = relationship.type();
                                    for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                        recordShips.put(entry.getKey(), entry.getValue());
                                    }
                                    recordShips.put("rela", rela);
                                    recordShips.put("id", id);
                                    recordShips.put("source", sourceId);
                                    recordShips.put("target", targetId);
                                    shipIds.add(id);
                                    if (!recordShips.isEmpty()) {
                                        ships.add(recordShips);
                                    }
                                }
                            }
                        }
                        else if (NEO4J_LIST_TYPE.equals(typeName)) {
                            Iterable<Value> values = pair.value().values();
                            Value listVals = values.iterator().next();
                            String listTypeName = listVals.type().name();
                            if (NEO4J_RELATIONSHIP_TYPE.equals(listTypeName)) {
                                Relationship relationship = listVals.asRelationship();
                                String id = Long.toString(relationship.id());
                                if (!shipIds.contains(id)) {
                                    recordShips = new HashMap<>(16);
                                    String sourceId = Long.toString(relationship.startNodeId());
                                    String targetId = Long.toString(relationship.endNodeId());
                                    for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                        recordShips.put(entry.getKey(), entry.getValue());
                                    }
                                    recordShips.put("id", id);
                                    recordShips.put("source", sourceId);
                                    recordShips.put("target", targetId);
                                    shipIds.add(id);
                                    if (!recordShips.isEmpty()) {
                                        recordShips.put("labelList",labelAndTypeMap.get("type(r)"));
                                        ships.add(recordShips);
                                    }
                                }
                            }
                        }
                        else if (NEO4J_MAP_TYPE.equals(typeName)) {
                            rss.put(pair.key(), pair.value().asMap());
                        }
                        else {
                            labelAndTypeMap.put(pair.key(),pair.value());
                            if (!rss.isEmpty()) {

                                nodes.add(rss);
                            }
                        }
                    }
                }
                nodeAndShip.put("node", nodes);
                nodeAndShip.put("relationship", ships);
            }
        } catch (Exception e) {
            logger.error("执行getGraphNodeAndShip()出错:{}", e.toString());
            throw e;
        }
        return nodeAndShip;
    }
    /**
     * 获取节点列表
     * 匹配所有类型的节点,可以是节点,关系,数值,路径
     *
     * @param cypher cypher语句
     * @return List<HashMap < String, Object>>
     */
    public List<HashMap<String, Object>> getNodeList(String cypher) {
        List<HashMap<String, Object>> nodes = new ArrayList<>();
        try {
            StatementResult statementResult = this.executeCypher(cypher);
            if (statementResult.hasNext()) {
                for (Record record : statementResult.list()) {
                    HashMap rss = new HashMap(16);
                    for (Pair<String, Value> pair : record.fields()) {
                        String typeName = pair.value().type().name();
                        if (NEO4J_NULL_TYPE.equals(typeName)) {
                            continue;
                        } else if (NEO4J_NODE_TYPE.equals(typeName)) {
                            Node node = pair.value().asNode();
                            for (Map.Entry<String, Object> entry : node.asMap().entrySet()) {
                                rss.put(entry.getKey(), entry.getValue());
                            }
                        } else if (NEO4J_RELATIONSHIP_TYPE.equals(typeName)) {
                            Relationship relationship = pair.value().asRelationship();
                            for (Map.Entry<String, Object> entry : relationship.asMap().entrySet()) {
                                rss.put(entry.getKey(), entry.getValue());
                            }
                        } else if (NEO4J_MAP_TYPE.equals(typeName)) {
                            rss.put(pair.key(), pair.value().asMap());
                        } else if (NEO4J_LIST_TYPE.equals(typeName)) {
                            rss.put(pair.key(), pair.value().asList());
                        } else if (NEO4J_PATH_TYPE.equals(typeName)) {
                        } else {
                            String key = pair.key().replace("\"","");
                            String value = String.valueOf(pair.value()).replace("\"","");
                            rss.put(key, value);
                        }
                    }
                    nodes.add(rss);
                }
            }
        } catch (Exception e) {
            logger.error("执行getNodeList()出错:{}", e.toString());
            throw e;
        }
        return nodes;
    }

    /**
     * 获取节点信息
     *
     * @param cypher
     * @param type
     * @param <T>
     * @return
     */
    public <T> List<T> GetEntityItemList(String cypher, Class<T> type) {
        List<HashMap<String, Object>> nodes = this.getGraphNode(cypher);
        return this.hashMapToObject(nodes, type);
    }

    /**
     * @param cypher
     * @param type
     * @param <T>
     * @return
     */
    public <T> T getEntityItem(String cypher, Class<T> type) {
        HashMap<String, Object> rss = new HashMap<>(16);
        try {
            StatementResult result = this.executeCypher(cypher);
            if (result.hasNext()) {
                Record record = result.next();
                for (Value value : record.values()) {
                    if (NEO4J_NODE_TYPE.equals(value.type().name())) {
                        for (Map.Entry<String, Object> entry : value.asNode().asMap().entrySet()) {
                            String key = entry.getKey();
                            if (rss.containsKey(key)) {
                                String oldValue = String.valueOf(rss.get(key));
                                String newValue = String.join(",", oldValue, String.valueOf(entry.getValue()));
                                rss.replace(key, newValue);
                            } else {
                                rss.put(key, entry.getValue());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getEntityItem()出错:{}", e.toString());
            e.printStackTrace();
        }
        return this.hashMapToObjectItem(rss, type);
    }

    public HashMap<String, Object> getEntity(String cypher) {
        HashMap<String, Object> rss = new HashMap<>(16);
        try {
            StatementResult result = this.executeCypher(cypher);
            if (result.hasNext()) {
                Record record = result.next();
                for (Value value : record.values()) {
                    if (NEO4J_NODE_TYPE.equals(value.type().name())) {
                        for (Map.Entry<String, Object> entry : value.asNode().asMap().entrySet()) {
                            String key = entry.getKey();
                            if (rss.containsKey(key)) {
                                String oldValue = String.valueOf(rss.get(key));
                                String newValue = String.join(",", oldValue, String.valueOf(entry.getValue()));
                                rss.replace(key, newValue);
                            } else {
                                rss.put(key, entry.getValue());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getEntity()出错:{}", e.toString());
            throw e;
        }
        return rss;
    }

    public Integer executeScalar(String cypher) {
        Integer count = 0;
        try {
            StatementResult result = this.executeCypher(cypher);
            if (result.hasNext()) {
                Record record = result.next();
                for (Value value : record.values()) {
                    if (INTEGER.equals(value.type().name())) {
                        count = Integer.valueOf(value.toString());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行executeScalar()出错:{}", e.toString());
            e.printStackTrace();
        }
        return count;
    }

    public HashMap<String, Object> getRelevantEntity(String cypher) {
        HashMap<String, Object> rss = new HashMap<>(16);
        try {
            StatementResult resultNode = this.executeCypher(cypher);
            if (resultNode.hasNext()) {
                for (Record record : resultNode.list()) {
                    Map<String, Object> map = record.asMap();
                    String key = String.valueOf(map.get("key"));
                    if (rss.containsKey(key)) {
                        String oldValue = String.valueOf(rss.get(key));
                        String newValue = String.join(",",oldValue,String.valueOf(map.get("value")));
                        rss.replace(key, newValue);
                    } else {
                        rss.put(key, map.get("value"));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行getRelevantEntity()出错:{}", e.toString());
            e.printStackTrace();
        }
        return rss;
    }

    /**
     * 多个hashmap to object
     *
     * @param maps    map
     * @param objType 对象类型
     * @return List<T>
     */
    public <T> List<T> hashMapToObject(List<HashMap<String, Object>> maps, Class<T> objType) {
        try {
            List<T> list = new ArrayList<>();
            for (HashMap<String, Object> map : maps) {
                T instance = objType.newInstance();
                // 该方法获取列名.获取一系列字段名称.例如name,age...
                Iterator iter = map.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = String.valueOf(entry.getKey());
                    Object value = entry.getValue();
                    if (SERIALVERSIONUID.equals(key.toLowerCase())) {
                        continue;
                    }
                    // 获取field对象
                    Field[] declaredFields = objType.getDeclaredFields();
                    List<String> strings = new ArrayList<>();
                    for (int i = 0; i < declaredFields.length; i++) {
                        strings.add(declaredFields[i].getName());
                    }
                    if(strings.contains(key)){
                        Field field = objType.getDeclaredField(key);
                        if (Objects.nonNull(field)) {
                            field.setAccessible(true);
                            if (field.getType() == int.class || field.getType() == Integer.class) {
                                if (null == value || StringUtils.isEmpty(String.valueOf(value))) {
                                    field.set(instance, 0);
                                } else {
                                    field.set(instance, Integer.parseInt(String.valueOf(value)));
                                }
                                continue;
                            }
                            else if (field.getType() == long.class || field.getType() == Long.class) {
                                if (value == null || StringUtils.isEmpty(String.valueOf(value))) {
                                    field.set(instance, 0);
                                } else {
                                    field.set(instance, Long.parseLong(String.valueOf(value)));
                                }
                                continue;
                            }
                            else {
                                field.set(instance, value);
                                continue;
                            }
                        }
                    }

                }
                list.add(instance);
            }
            return list;
        } catch (Exception e) {
            logger.error("执行hashMapToObject()出错:{}", e.toString());
            throw new RuntimeException(e);
        }
    }


    public <T> T hashMapToObjectItem(HashMap<String, Object> map, Class<T> type) {
        try {
            T instance = type.newInstance();
            Iterator iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = entry.getKey().toString();
                Object value = entry.getValue();
                if (SERIALVERSIONUID.equals(key.toLowerCase())) {
                    continue;
                }
                Field field = type.getDeclaredField(key);
                if (null != field) {
                    field.setAccessible(true);
                    if (field.getType() == int.class || field.getType() == Integer.class) {
                        if (value == null || StringUtils.isEmpty(String.valueOf(value))) {
                            field.set(instance, 0);
                        } else {
                            field.set(instance, Integer.parseInt(String.valueOf(value)));
                        }
                    } else if (field.getType() == long.class || field.getType() == Long.class) {
                        if (value == null || StringUtils.isEmpty(String.valueOf(value))) {
                            field.set(instance, 0);
                        } else {
                            field.set(instance, Long.parseLong(value.toString()));
                        }
                    } else {
                        field.set(instance, value);
                    }
                }
            }
            return instance;
        } catch (Exception e) {
            logger.error("执行hashMapToObjectItem()出错:{}", e.toString());
            throw new RuntimeException(e);
        }
    }

    public String getFilterPropertiesJson(String jsonStr) {
        // 去掉key的引号
        return jsonStr.replaceAll("\"(\\w+)\"(\\s*:\\s*)", "$1$2");
    }

    public <T> String getkeyvalCypher(T obj) {
        Map<String, Object> map = new HashMap<>(16);
        List<String> sqlList = new ArrayList<>();
        // 得到类对象
        Class clasObj = obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = clasObj.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            Class type = f.getType();

            // 设置哪些属性是可以访问的
            f.setAccessible(true);
            Object val;
            try {
                val = f.get(obj);
                if (val == null) {
                    val = "";
                }
                String sql;
                String key = f.getName();
                System.out.println("key:" + key + "type:" + type);
                if (val instanceof Integer) {
                    // 得到此属性的值,设置键值
                    map.put(key, val);
                    sql = "n." + key + "=" + val;
                } else if (val instanceof String[]) {
                    // 如果为true则强转成String数组
                    String[] arr = (String[]) val;
                    String v = "";
                    for (int j = 0; j < arr.length; j++) {
                        arr[j] = "'" + arr[j] + "'";
                    }
                    v = String.join(",", arr);
                    sql = "n." + key + "=[" + val + "]";
                } else if (val instanceof List) {
                    // 如果为true则强转成String数组
                    List<String> arr = (ArrayList<String>) val;
                    List<String> aa = new ArrayList<>();
                    String v = "";
                    for (String s : arr) {
                        s = "'" + s + "'";
                        aa.add(s);
                    }
                    v = String.join(",", aa);
                    sql = "n." + key + "=[" + v + "]";
                } else {
                    // 得到此属性的值,设置键值
                    map.put(key, val);
                    sql = "n." + key + "='" + val + "'";
                }

                sqlList.add(sql);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        String finasql = String.join(",", sqlList);
        System.out.println("单个对象的所有键值==反射==" + map.toString());
        return finasql;
    }

}

;