Java/Spring Boot

[Spring Boot] Neo4j

hh_lin 2022. 5. 1. 19:17

1. Neo4j

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

 

 

 

 

 

 

 

 

 

 

2. 의존성 추가

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

 

 

 

 

 

 

 

 

3. Neo4j 설치 및 실행 (도커)

① Neo4j 설치

docker run -p 7474:7474 -p 7687:7687 -d --name neo4j_boot neo4j

- 7474 : http 용

- 7687 : Bolt 프로토콜 용

 

 

 

② Neo4j Browser

  • http://localhost:7474/browser
  • 기본 패스워드 : neo4j
    패스워드 변경 시 appliation.properties 변경 필요
    - spring.neo4j.authentication.username=neo4j
    - spring.neo4j.authentication.password=1111

 

 

 

 

 

 

 

 

 

 

4. 스프링 데이터 Neo4J

  • Neo4jTemplate (Deprecated)
  • SessionFactory (Spring 버전이 낮은 경우 org.neo4j.ogm import해서 사용 가능한 듯)
  • Neo4jRepository

 

 

 

# Account

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

   // getter, setter 생략
}

 

 

 

# Role

@Node
public class Role {
   @Id
   @GeneratedValue
   private Long id;
   private String name;
   
   // getter, setter 생략
}

 

 

 

# AccountRepository

public interface AccountRepository extends Neo4jRepository<Account, Long> {
}

 

 

 

# Neo4jRunner

@Component
public class Neo4jRunner implements ApplicationRunner {

   @Autowired
   AccountRepository accountRepository;

   @Override
   public void run(ApplicationArguments args) throws Exception {

      Account account = new Account();
      account.setEmail("admin@mail.com");
      account.setUsername("Admin");

      Role role = new Role();
      role.setName("admin");

      account.getRoles().add(role);

      accountRepository.save(account);

      System.out.println("finished");
   }
}

 

 

 

- Role 없는 hhlin Account 저장

 

 

 

- admin Role을 가진 Admin Account 저장

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com