Spring Data JPA 사용하기

2020. 9. 1. 14:43 Spring Framework/Spring boot

Spring Data JPA란?

  Spring Project 중 하나다. Spring Data Project는 여러가지 Data Repository(JPA, mongoDB, Neo4j, Redis, Hadoop 등)를 지원한다. Data JPA는 JPA를 Spring에서 쉽게 사용하게 만든 프로젝트이다.


Entity

  • AbstractPersistable<PK> : PK Type에 Primary Key가 자동으로 셋팅된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@Entity(name = "tbl_user")
public class User extends AbstractPersistable<Integer> {
 
    private String username;
    private String nickName;
    private String address;
 
    @Temporal(TemporalType.TIMESTAMP)
    private Date createDate = new Date();
 
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Order> orders = new ArrayList<>();
 
    // getter and setter
 
    public void addOrder(Order order) {
        this.orders.add(order);
    }
 
    @Override
    public String toString() {
        return "User{" +
                "userId=" + getId() +
                ", username='" + username + '\'' +
                ", nickName='" + nickName + '\'' +
                ", address='" + address + '\'' +
                ", orders=" + orders +
                '}';
    }
}
 
@Entity(name = "tbl_order")
public class Order extends AbstractPersistable<Integer> {
 
    private String orderName;
    private String note;
    private int price;
 
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;
 
    public Order() {
    }
 
    public Order(String orderName, String note, int price, User user) {
        this.orderName = orderName;
        this.note = note;
        this.price = price;
        this.user = user;
    }
 
    // getter and setter
 
    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + getId() +
                ", orderName='" + orderName + '\'' +
                ", note='" + note +
                '}' "\n";
    }
}


User Repository

1
2
3
4
5
import net.woniper.jpa.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
 
public interface UserRepository extends JpaRepository<User, Integer> {
}


Order Repository

  • findByOrderNameAndUser는 orderName과 uesrId 조건으로 Order를 조회한다.
  • 이를 QueryMethod라고 한다. (참고)
1
2
3
4
public interface OrderRepository extends JpaRepository<Order, Integer> {
 
    Order findByOrderNameAndUser(String orderName, User user);
}


CRUD Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import net.woniper.jpa.domain.Order;
import net.woniper.jpa.domain.User;
import net.woniper.jpa.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import java.util.Date;
 
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootDataJpaApplication.class)
public class CrudTest {
 
    @Autowired private UserRepository userRepository;
 
    private User user;
 
    @Before
    public void setUp() throws Exception {
        user = new User();
        user.setUsername("lkw1989");
        user.setNickName("woniper");
        user.setAddress("seoul");
        user.addOrder(new Order("order1""test1"100, user));
        user.addOrder(new Order("order2""test2"100, user));
        user.setCreateDate(new Date());
        userRepository.save(user);
        userRepository.flush();
    }
 
    @Test
    public void testFind() throws Exception {
        User findUser = userRepository.findOne(user.getId());
        assertEquals(user.getId(), findUser.getId());
    }
 
    @Test
    public void testUpdate() throws Exception {
        user.setAddress("update address");
        userRepository.saveAndFlush(user);
 
        User updateUser = userRepository.findOne(user.getId());
        assertEquals(user.getAddress(), updateUser.getAddress());
    }
 
    @Test
    public void testDelete() throws Exception {
        userRepository.delete(user);
        userRepository.flush();
 
        User deleteUser = userRepository.findOne(user.getId());
        assertNull(deleteUser);
    }
 
    @Test
    public void testContexts() throws Exception {
        assertNotNull(userRepository);
    }
}


Find Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import net.woniper.jpa.domain.Order;
import net.woniper.jpa.domain.User;
import net.woniper.jpa.repository.OrderRepository;
import net.woniper.jpa.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import java.util.Date;
 
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootDataJpaApplication.class)
public class FindTest {
 
    @Autowired private UserRepository userRepository;
    @Autowired private OrderRepository orderRepository;
 
    private User user;
 
    @Before
    public void setUp() throws Exception {
        user = new User();
        user.setUsername("lkw1989");
        user.setNickName("woniper");
        user.setAddress("seoul");
        for (int i = 0; i < 10; i++) {
            user.addOrder(new Order("order" + i, "test" + i, 100, user));
        }
        user.setCreateDate(new Date());
        userRepository.save(user);
        userRepository.flush();
    }
 
    @Test
    public void testFindAnd() throws Exception {
        Order o = getOrder();
        Order order = orderRepository.findByOrderNameAndUser(o.getOrderName(), user);
        assertEquals(o.getId(), order.getId());
    }
 
    @Test
    public void testFindPaging() throws Exception {
        Pageable pageable = new PageRequest(05);
        Page<Order> orders = orderRepository.findAll(pageable);
        assertEquals(5, orders.getSize());
    }
 
    private Order getOrder() {
        return user.getOrders().get(0);
    }
 
    @Test
    public void testContexts() throws Exception {
        assertNotNull(userRepository);
    }
}


출처 : https://blog.woniper.net/270?category=699184