上一篇:什么是Neo4J? | 带你读《SpringBoot实战教程》之三十
下一篇:SpringBoot如何整合Redis(单机版)? | 带你读《SpringBoot实战教程》之三十二
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。
SpringBoot整合Neo4j
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
在全局配置文件application.properties中添加:
spring.data.neo4j.uri=http://localhost:7474
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=123
UserNode:
//表示节点类型
@NodeEntity(label="User")
public class UserNode {
@GraphId
private Long nodeId;
@Property
private String userId;
@Property
private String name;
@Property
private int age;
//get,set方法省略
}
UserRelation:
//表示关系类型
@RelationshipEntity(type="UserRelation")
public class UserRelation {
@GraphId
private Long id;
@StartNode
private UserNode startNode;
@EndNode
private UserNode endNode;
//get,set方法省略
}
dao:
UserRepository:
@Component
public interface UserRepository extends GraphRepository<UserNode> {
@Query("MATCH (n:User) RETURN n ")
List<UserNode> getUserNodeList();
@Query("create (n:User{age:{age},name:{name}}) RETURN n ")
List<UserNode> addUserNodeList(@Param("name") String name, @Param("age")int age);
}
UserRelationRepository:
@Component
public interface UserRelationRepository extends GraphRepository<UserRelation> {
@Query("match p=(n:User)<-[r:UserRelation]->(n1:User) where n.userId={firstUserId} and n1.userId={secondUserId} return p")
List<UserRelation> findUserRelationByEachId(@Param("firstUserId") String firstUserId, @Param("secondUserId") String secondUserId);
@Query("match (fu:User),(su:User) where fu.userId={firstUserId} and su.userId={secondUserId} create p=(fu)-[r:UserRelation]->(su) return p")
List<UserRelation> addUserRelation(@Param("firstUserId") String firstUserId, @Param("secondUserId") String secondUserId);
}
UserService:
@Service
public class UserService {
@Autowired
private UserRepositoty userRepositoty;
public void addUserNode(UserNode userNode) {
userRepository.addUserNodeList(userNode.getName(), userNode.getAge());
}
}
Neo4jController:
@Controller
public class Neo4jController {
@@Autowired
private UserService userService;
@RequestMapping("/saveUser")
@ResponseBody
public String saveUserNode() {
UserNode node = new UserNode();
node.setNodeId(1l);
node.setUserId("666");
node.setName("张三");
node.setAge(25);
UserService.addUserNode(node);
return "success";
}
}
在启动类中添加所有需要扫描的包:
@SpringBootApplication(scanBasePackages="com.qianfeng")
@EnableNeo4jRepositories(basePackages="com.qianfeng.dao")
@EntityScan(basePackages="com.qianfeng.pojo")
执行结果:
打包发布
1、需要打成war包
2、添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
3、启动类继承SpringBootServletInitializer,重写configure方法
需要打包的工程如图所示:
war包地址:
然后就可以部署到自己的服务器了。