본문 바로가기

JAVA/JPA

[Spring] JPA Sample

 
디렉토리 구조
java
    com/
        controller/
            help/
                TestJpaSampleController
        service/
            help/
                TestJpaSampleService
        domain/
            db/
                bncadm/
                    testsample/
                        TestSample    
                        TestSampleRepository
test
    com/
        controller/
            help/
                TestJpaSamplceControllerTest
 
  1. DB에 테이블 만들기
 
CREATE TABLE test_sample (
    id VARCHAR(20) NOT NULL,
        name VARCHAR(20) NOT NULL, 
        age Integer,
    ins_tm TIMESTAMP DEFAULT NOW(), 
    primary key(id)
)
 
  1. 객체 만들기 
 
@Getter
@Setter
@NoArgsConstructor
@Entity(name = "test_sample")  // Entity로 지정한 클래스만 JPA에서 관리 대상으로 취급한다.
public class TestSample {
 
    @Id // pk값에 해당하는 컬럼 지정
    private String id;
 
    @Column
    private String name;
 
    @Column
    private Integer age;
 
    @Column(name="ins_tm") // 객체명과 DB 컬럼명을 다르게 하고 싶은 경우, DB 컬럼명으로 설정할 이름을 name 속성으로 적는다.
    @Temporal(TemporalType.TIMESTAMP) // 시간 날짜 타입을 지정하는 annotation
    private Date insTm;
}
 
  1. JpaRepository 를 상속받은 interface 만들기 (객체별)
 
@Repository
public interface TestSampleRepository extends JpaRepository<TestSample, String> {
    // 1. 위의 extends JpaRepository<도메인객체클래스명, pk타입> 설정
    // 2. 기본 내장 기능인 findById, findAll(), save(), delete() 사용 가능한 상태.
}
 
  1. Controller, Service 만들기 
 
@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping(value = "/sample")
public class TestJpaSampleController {
 
 
    private final TestJpaSampleService testJpaSampleService;
 
 
    @PostMapping("/create")
    @ResponseBody
    public TestSample create(@RequestBody TestSample param){
        return testJpaSampleService.create(param);
    }
 
 
 
 
    @PostMapping("/read")
    @ResponseBody
    public Optional<TestSample> read(@RequestBody TestSample param){
        return testJpaSampleService.read(param.getId());
    }
 
 
 
 
    @PostMapping("/update")
    @ResponseBody
    public TestSample update(@RequestBody TestSample param){
        return testJpaSampleService.update(param);
    }
 
 
 
 
    @PostMapping("/delete")
    @ResponseBody
    public void delete(@RequestBody TestSample param){
        testJpaSampleService.delete(param);
    }
}
 
 
@Service
@Slf4j
@RequiredArgsConstructor
public class TestJpaSampleService {
 
 
    private final TestSampleRepository testSampleRepository;
 
 
    public TestSample create(TestSample param){
        // 1. 객체 만들기 (trasient 상태)
        TestSample testSample = new TestSample();
        // 2. 객체에 값 넣기
        testSample.setId(param.getId());
        testSample.setName(param.getName());
        testSample.setAge(param.getAge());
        testSample.setInsTm(param.getInsTm());
 
        // 3. 객체를 영속성 상태로 만들기
//        testSampleRepository.save(param); // 바로 넣어줘야하는 경우 따로 처리하지 않아도 무방
 
        return testSampleRepository.save(testSample);
    }
 
 
    public Optional<TestSample> read(String id) {
        return testSampleRepository.findById(id);
    }
 
 
    public TestSample update(TestSample param) {
        // create와 동일한 방법으로 진행 시 id값 비교하여 가져오고 id값이 존재하면 update해줌, 없으면 insert 진행
//        testSampleRepository.save(param);
 
        TestSample result;
        Optional<TestSample> testSample = testSampleRepository.findById(param.getId());
        if(testSample.isPresent()){  // id에 해당하는 값이 있었는 지 확인
            TestSample updateSample = testSample.get();
            updateSample.setName(param.getName()); // 가져온 객체 정보 변경
            result = testSampleRepository.save(updateSample); // 변경된 정보로 save 진행
        } else{
            result = null;
        }
 
        return result;
    }
 
 
    public void delete(TestSample param) {
        testSampleRepository.delete(param);
    }
 
 
    public long getCount(){
        return testSampleRepository.count();
    }
}
 
  1. Testcase 만들기
 
@AutoConfigureMockMvc
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.MOCK,
        properties = BncApplication.PROPERTIES
)
public class TestJpaSamplceControllerTest {
 
 
    @Autowired
    private MockMvc mockMvc;
 
    @Autowired
    private TestJpaSampleService testJpaSampleService;
 
    @Autowired
    private TestSampleRepository testSampleRepository;
 
    @Autowired
    private ObjectMapper objectMapper;
 
    @Test
    public void createRepositoryTest() {
        TestSample testSample = new TestSample();
        testSample.setId("test_id");
        testSample.setName("test_name");
        testSample.setAge(22);
//        testSample.setInsTm(new Date()); //
        testSampleRepository.save(testSample);
 
 
        System.out.println("----------createRepositoryTest-------------");
        System.out.println(testSampleRepository.findById("test_id").get());
    }
 
 
    @Test
    public void readRepositoryTest() {
        System.out.println("----------readRepositoryTest-------------");
        System.out.println(testSampleRepository.findById("test_id").get());
    }
 
 
    @Test
    public void updateRepositoryTest() {
 
 
        // 방법 1 동일한 객체에 대한 정보로 저장 시 PK값이 있으면 UPDATE, 없으면 INSERT 새롭게.
//        TestSample testSample = new TestSample();
//        testSample.setId("test_id");
//        testSample.setName("변경");
//        testSample.setAge(22);
//        testSample.setInsTm(new Date());
//        testSampleRepository.save(testSample);
 
 
        // 방법 2 PK값으로 가져온 뒤 정보 변경해서 넣기
        Optional<TestSample> getSample = testSampleRepository.findById("test_id");
        if (getSample.isPresent()) {
            TestSample updateSample = getSample.get();
            updateSample.setName("변경하기");
            testSampleRepository.save(updateSample);
        }
 
 
        System.out.println("----------updateRepositoryTest-------------");
        System.out.println(testSampleRepository.findById("test_id").get());
    }
 
 
    @Test
    public void deleteRepositoryTest() {
        TestSample testSample = new TestSample();
        testSample.setId("test_id");
 
 
        Optional<TestSample> getSample = testSampleRepository.findById("test_id");
        if (getSample.isPresent()) {
            TestSample deleteSample = getSample.get();
            testSampleRepository.delete(deleteSample);
        }
        System.out.println("----------deleteRepositoryTest-------------");
        System.out.println(testSampleRepository.findById("test_id").get());
    }
 
 
 
 
    // Controller 부터 테스트 진행하기.
 
 
    @Test
    public void createTest() throws Exception {
 
 
        TestSample testSample = new TestSample();
        testSample.setId("test_id");
        testSample.setName("test_name");
        testSample.setAge(22);
//        testSample.setInsTm(new Date()); //
 
 
        String json = objectMapper.writeValueAsString(testSample);
 
 
        ResultActions resultActions = mockMvc.perform(post("/sample/create")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json));
 
 
        resultActions.andDo(print());
    }
 
 
    @Test
    public void readTest() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("id", "test_id");
 
 
        String json = objectMapper.writeValueAsString(map);
 
 
        ResultActions resultActions = mockMvc.perform(post("/sample/read")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json));
 
 
        resultActions.andDo(print());
    }
 
 
    @Test
    public void updateTest() throws Exception {
 
 
        TestSample testSample = new TestSample();
        testSample.setId("test_id");
        testSample.setName("변경");
        testSample.setAge(22);
        testSample.setInsTm(new Date());
 
 
        String json = objectMapper.writeValueAsString(testSample);
 
 
        ResultActions resultActions = mockMvc.perform(post("/sample/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json));
 
 
        resultActions.andDo(print());
    }
 
 
    @Test
    public void deleteTest() throws Exception {
        TestSample testSample = new TestSample();
        testSample.setId("test_id");
 
 
        String json = objectMapper.writeValueAsString(testSample);
 
 
        ResultActions resultActions = mockMvc.perform(post("/sample/delete")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json));
 
 
        resultActions.andDo(print());
    }
}