ORM(Spring data jpa)

spring-data-jpa , hibernate , orm

pom.xml

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

application.propertise

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

application.yml

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: ''
        url: jdbc:mysql://localhost:3306/test
        username: root
    jpa:
        properties:
            hibernate:
                hbm2ddl:
                    auto: create-drop

User 도메인 작성

@Entity
@Data
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Repository interface 작성

public interface UserRepository extends JpaRepository<User, Long> {

    User findByName(String name);

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);

}

테스트 코드 작성

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {

        // 데이터 10건 생성
        userRepository.save(new User("AAA", 10));
        userRepository.save(new User("BBB", 20));
        userRepository.save(new User("CCC", 30));
        userRepository.save(new User("DDD", 40));
        userRepository.save(new User("EEE", 50));
        userRepository.save(new User("FFF", 60));
        userRepository.save(new User("GGG", 70));
        userRepository.save(new User("HHH", 80));
        userRepository.save(new User("III", 90));
        userRepository.save(new User("JJJ", 100));

        // findAll, 전체조회
        Assert.assertEquals(10, userRepository.findAll().size());

        // findByName, 이름이 FFF인 사용자 User
        Assert.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());

        // findUser, 이름이 FFF인 사용자 User
        Assert.assertEquals(60, userRepository.findUser("FFF").getAge().longValue());

        // findByNameAndAge, 이름이 FFF인 , 나이는 60인 사용자 User
        Assert.assertEquals("FFF", userRepository.findByNameAndAge("FFF", 60).getName());

        // 이름 AAA인 User 삭제
        userRepository.delete(userRepository.findByName("AAA"));

        // findAll, 전체조회하여 정상 삭제 되었는지 확인
        Assert.assertEquals(9, userRepository.findAll().size());

    }
}

끝!

Last updated