当前位置:   article > 正文

springboot使用neo4j_springboot连接neo4j

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

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;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529
  • 530
  • 531
  • 532
  • 533
  • 534
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551
  • 552
  • 553
  • 554
  • 555
  • 556
  • 557
  • 558
  • 559
  • 560
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • 577
  • 578
  • 579
  • 580
  • 581
  • 582
  • 583
  • 584
  • 585
  • 586
  • 587
  • 588
  • 589
  • 590
  • 591
  • 592
  • 593
  • 594
  • 595
  • 596
  • 597
  • 598
  • 599
  • 600
  • 601
  • 602
  • 603
  • 604
  • 605
  • 606
  • 607
  • 608
  • 609
  • 610
  • 611
  • 612
  • 613
  • 614
  • 615
  • 616
  • 617
  • 618
  • 619
  • 620
  • 621
  • 622
  • 623
  • 624
  • 625
  • 626
  • 627
  • 628
  • 629
  • 630
  • 631
  • 632
  • 633
  • 634
  • 635
  • 636
  • 637
  • 638
  • 639
  • 640
  • 641
  • 642
  • 643
  • 644
  • 645
  • 646
  • 647
  • 648
  • 649
  • 650
  • 651
  • 652
  • 653
  • 654
  • 655
  • 656
  • 657
  • 658
  • 659
  • 660
  • 661
  • 662
  • 663
  • 664
  • 665
  • 666
  • 667
  • 668
  • 669
  • 670
  • 671
  • 672
  • 673
  • 674
  • 675
  • 676
  • 677
  • 678
  • 679
  • 680
  • 681
  • 682
  • 683
  • 684
  • 685
  • 686
  • 687
  • 688
  • 689
  • 690
  • 691
  • 692
  • 693
  • 694
  • 695
  • 696
  • 697
  • 698
  • 699
  • 700
  • 701
  • 702
  • 703
  • 704
  • 705
  • 706
  • 707
  • 708
  • 709
  • 710
  • 711
  • 712
  • 713
  • 714
  • 715
  • 716
  • 717
  • 718
  • 719
  • 720
  • 721
  • 722
  • 723
  • 724
  • 725
  • 726
  • 727
  • 728
  • 729
  • 730
  • 731
  • 732
  • 733
  • 734
  • 735
  • 736
  • 737
  • 738
  • 739
  • 740
  • 741
  • 742
  • 743
  • 744
  • 745
  • 746
  • 747
  • 748
  • 749
  • 750
  • 751
  • 752
  • 753
  • 754
  • 755
  • 756
  • 757
  • 758
  • 759
  • 760
  • 761
  • 762
  • 763
  • 764
  • 765
  • 766
  • 767
  • 768
  • 769
  • 770
  • 771
  • 772
  • 773
  • 774
  • 775
  • 776
  • 777
  • 778
  • 779
  • 780
  • 781
  • 782
  • 783
  • 784
  • 785
  • 786
  • 787
  • 788
  • 789
  • 790
  • 791
  • 792
  • 793
  • 794
  • 795
  • 796
  • 797
  • 798
  • 799
  • 800
  • 801
  • 802
  • 803
  • 804
  • 805
  • 806
  • 807
  • 808
  • 809
  • 810
  • 811
  • 812
  • 813
  • 814
  • 815
  • 816
  • 817
  • 818
  • 819
  • 820
  • 821
  • 822
  • 823
  • 824
  • 825
  • 826
  • 827
  • 828
  • 829
  • 830
  • 831
  • 832
  • 833
  • 834
  • 835
  • 836
  • 837
  • 838
  • 839
  • 840
  • 841
  • 842
  • 843
  • 844
  • 845
  • 846
  • 847
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/641551
推荐阅读
相关标签
  

闽ICP备14008679号