上文建模完成了接下来项目引入相关包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
新建工具类MysqlMetaTool.java并添加如下方法
package com.example.demo.neo4j.dbkit;
import com.example.demo.neo4j.entity.ColumnEntity;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import com.mysql.cj.result.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Description TODO
* @Author 姚仲杰#80998699
* @Date 2021/2/6 15:15
*/
public class MysqlMetaTool {
private final static Logger log = LoggerFactory.getLogger(MysqlMetaTool.class);
public List<ColumnEntity> getNodesFromMysqlByTableName(String jdbcUrl,
String tableName) {
List<ColumnEntity> list=new ArrayList<>();
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(jdbcUrl);
st = conn.prepareStatement(
"select * from information_schema.columns where table_name ='" + tableName + "'");
rs = st.executeQuery();
while (rs.next()) {
RowMapper<ColumnEntity> rowMapper=new RowMapper<>(ColumnEntity.class);
ColumnEntity columnEntity = rowMapper.rowMap(rs);
list.add(columnEntity);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
log.info("Mysql connection close");
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
RowMapper.java
package com.example.demo.neo4j.dbkit;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Description TODO
* @Author 姚仲杰#80998699
* @Date 2021/2/6 15:42
*/
public class RowMapper<T> {
private Class<?> cl;
public RowMapper(Class<?> cl) {
this.cl = cl;
}
public T rowMap(ResultSet rs) throws SQLException {
try {
Field[] fields = cl.getDeclaredFields();
T entity = (T) cl.newInstance();
com.mysql.cj.result.Field[] n = ((ResultSetImpl) rs).getMetadata().getFields();
Field[] intersection = getIntersection(fields, n);
for (Field f : intersection) {
f.setAccessible(true);
this.typeMapper(f, entity, rs);
f.setAccessible(false);
}
return entity;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**已sql查询为准求实体交集避免报错
* @param m
* @param n
* @return
*/
private static Field[] getIntersection(Field[] m, com.mysql.cj.result.Field[] n)
{
Set<String> set = new HashSet<String>();
for (Field field : m) {
set.add(field.getName());
}
List<String> list=new ArrayList<>();
for (com.mysql.cj.result.Field field : n) {
list.add(field.getColumnLabel());
}
Set<String> result=new HashSet<String>();
for (String s : list) {
if (set.contains(CamelCase.underlineToCamel(s))){
result.add(CamelCase.underlineToCamel(s));
}
}
Field[] fields=new Field[result.size()];
int i=0;
for (Field field : m) {
if (result.contains(field.getName())){
fields[i]=field;
i++;
}
}
return fields;
}
private void typeMapper(Field field, Object obj, ResultSet rs) throws Exception {
String type = field.getType().getName();
if (type.equals("java.lang.String")) {
field.set(obj, rs.getString(CamelCase.camelToUnderline(field.getName(),2)));
} else if (type.equals("int") || type.equals("java.lang.Integer")) {
field.set(obj, rs.getInt(CamelCase.camelToUnderline(field.getName(),2)));
} else if (type.equals("long") || type.equals("java.lang.Long")) {
field.set(obj, rs.getLong(CamelCase.camelToUnderline(field.getName(),2)));
} else if (type.equals("boolean") || type.equals("java.lang.Boolean")) {
field.set(obj, rs.getBoolean(CamelCase.camelToUnderline(field.getName(),2)));
} else if (type.equals("java.util.Date")) {
field.set(obj, rs.getDate(CamelCase.camelToUnderline(field.getName(),2)));
}
}
}
CamelCase.java
package com.example.demo.neo4j.dbkit;
/**
* @Description TODO
* @Author 姚仲杰#80998699
* @Date 2021/2/6 15:39
*/
public class CamelCase {
public static final char UNDERLINE = '_';
//驼峰转下划线
public static String camelToUnderline(String param, Integer charType) {
if (param == null || "".equals(param.trim())) {
return "";
}
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
}
if (charType == 2) {
sb.append(Character.toUpperCase(c)); //统一都转大写
} else {
sb.append(Character.toLowerCase(c)); //统一都转小写
}
}
return sb.toString();
}
//下划线转驼峰
public static String underlineToCamel(String param) {
if (param == null || "".equals(param.trim())) {
return "";
}
int len = param.length();
StringBuilder sb = new StringBuilder(len);
Boolean flag = false;
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c == UNDERLINE) {
flag = true;
continue; //标志设置为true,跳过
} else {
if (flag == true) {
//表示当前字符前面是"_" ,当前字符转大写
sb.append(Character.toUpperCase(param.charAt(i)));
flag = false;
} else {
sb.append(Character.toLowerCase(param.charAt(i)));
}
}
}
return sb.toString();
}
}
给实体打上neo4j 注解,并增加自增id属性
@NodeEntity(label = "Column")
public class ColumnEntity {
@Id
@GeneratedValue
private Long id;
新建dao
package com.example.demo.neo4j.dao;
import com.example.demo.neo4j.entity.ColumnBean;
import com.example.demo.neo4j.entity.ColumnEntity;
import org.springframework.data.neo4j.repository.Neo4jRepository;
/**
* @Description TODO
* @Author 姚仲杰#80998699
* @Date 2021/2/4 18:19
*/
public interface ColumnRepo extends Neo4jRepository<ColumnEntity,Long> {
}
编写controller
@Autowired
ColumnRepo columnRepo;
@RequestMapping("/createNodes")
public Result getNodes(){
MysqlMetaTool mysqlMetaTool=new MysqlMetaTool();
List<ColumnEntity> columns = mysqlMetaTool.getNodesFromMysqlByTableName(jdbcUrl, "t_user");
for (ColumnEntity column : columns) {
ColumnEntity columnEntity= columnRepo.save(column);
}
return Result.SUCCESS();
}