依赖
<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.*;
@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;
/**
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;
}
/**
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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();
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);
}
}
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);
}
}
}
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;
}
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;
}
public <T> List<T> GetEntityItemList(String cypher, Class<T> type) {
List<HashMap<String, Object>> nodes = this.getGraphNode(cypher);
return this.hashMapToObject(nodes, type);
}
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;
}
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();
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[] 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) {
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[]) {
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) {
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;
}
}