findCurrentUserBooks();}"> findCurrentUserBooks();}"> findCurrentUserBooks();}">
public interface BookRepository extends JpaRepository<Book, Long> { @Query("select b from Book b where b.author.id = ?#{principal.accountNonExpired.id}}") List<Book> findCurrentUserBooks();}
스프링 시큐리티가 지원하는 스프링 데이터와 연동
의존성 추가
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
<version>${spring-security.version}</version>
</dependency>
연관관계를 하나 만들자.
@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
@ManyToOne
private Account author;
}
public class DefaultDataGenerator implements ApplicationRunner {
@Autowired
AccountService accountService;
@Autowired
BookRepository bookRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
// keesun - spring
// whiteship - hibernate
Account keesun = createUser("keesun");
Account whiteship = createUser("whiteship");
createBook("spring", keesun);
createBook("hibernate", whiteship);
}
private Account createUser(String username) {
Account account = new Account();
account.setUsername(username);
account.setPassword("123");
account.setRole("USER");
return accountService.createAccount(account);
}
private void createBook(String title, Account author) {
Book book = new Book();
book.setTitle(title);
book.setAuthor(author);
bookRepository.save(book);
}
}
이러한 관계에서 /user 핸들러에서 뷰를 보여줄 때 책의 목록을 같이 보여주고 싶을 때
public interface BookRepository extends JpaRepository<Book, Long> {
@Query("select b from Book b where b.author.id = ?#{principal.account.id}}")
List<Book> findCurrentUserBooks();
}