Develop/Spring Boot

32. Neo4j Connection

자라선 2020. 7. 27. 17:27

Neo4j 는 노드간의 영관 관계를 영속화하는데 유리한 그래프 데이터베이스

관계형 데이터베이스보다는 조회가 빠르다는 장점이 있음

Neo4j는 하위호환성이 좋지 않다고 함.

# docker 컨테이너 생성
docker run -p 7474:7474 -p 7687:7687 -d --name noe4j_boot neo4j

http://localhost:7474/browser

기본 계정은 neo4j / neo4j

 

의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>

VO객체를 만듦

@NodeEntity
public class Account {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String username;
 
    private String email;
 
    @Relationship(type = "has")
    private Set<Role> roleSet = new HashSet<>();

레포지토리 인터페이스 정의

import org.springframework.data.neo4j.repository.Neo4jRepository;
public interface AccountRepository extends Neo4jRepository<Account, Long> {
}

Runner 코드

package me.tony.demospringboot;
import me.tony.demospringboot.account.Account;
import me.tony.demospringboot.account.AccountRepository;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
 
@Component
public class Neo4jRunner implements ApplicationRunner {
 
    @Autowired
    SessionFactory sessionFactory;
 
    @Autowired
    AccountRepository accountRepository;
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Account account = new Account();
        account.setUsername("account");
        account.setEmail("boot@naver.com");
 
        Role role = new Role();
        role.setName("Testadmin");
 
        account.getRoleSet().add(role);
 
//        Session session = sessionFactory.openSession();
//        session.save(account);
//        sessionFactory.close();
 
        accountRepository.save(account);
 
        System.out.println("finished");
    }
}