반응형
오늘은 16강, 17강을 수강하였다.
학습한 내용은 아래와 같다.
내 버전이 달라서인지 APPLICATION_JSON_UTF8 이 deprecated 되었다고 나오지만 그냥 진행하였다.
*hello.http
GET http://localhost:8080/api/helloWorld
###
GET http://localhost:8080/api/person/1
###
*PersonController
package com.fastcampus.javaallinone.project3.mycontact.controller;
import com.fastcampus.javaallinone.project3.mycontact.domain.Person;
import com.fastcampus.javaallinone.project3.mycontact.repository.PersonRepository;
import com.fastcampus.javaallinone.project3.mycontact.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RequestMapping(value = "/api/person")
@RestController
@Slf4j
public class PersonController {
@Autowired
private PersonService personService;
@Autowired
private PersonRepository personRepository;
@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id){
return personService.getPerson(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void postPerson(@RequestBody Person person) {
personService.put(person);
log.info("person -> {}" , personRepository.findAll());
}
}
*PersonControllerTest
package com.fastcampus.javaallinone.project3.mycontact.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
class PersonControllerTest {
@Autowired
private PersonController personController;
private MockMvc mockMvc;
@Test
void getPerson() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
mockMvc.perform(
MockMvcRequestBuilders.get("/api/person/1"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
void postPerson() throws Exception{
mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
mockMvc.perform(
MockMvcRequestBuilders.post("/api/person")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{ \"name\": \"martin2\",\n" +
" \"age\": 20,\n" +
" \"bloodType\": \"A\"}"))
.andDo(print())
.andExpect(status().isCreated());
}
}
*testdata.json
{
"name": "martin2",
"age": 20,
"bloodType": "A"
}
*Person.java
package com.fastcampus.javaallinone.project3.mycontact.domain;
import com.fastcampus.javaallinone.project3.mycontact.domain.dto.Birthday;
import lombok.*;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Data
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
@NotEmpty
@Column(nullable = false)
private String name;
@NonNull
@Min(1)
private int age;
private String hobby;
@NotEmpty
@NonNull
@Column(nullable = false)
private String bloodType;
private String address;
@Valid
@Embedded
private Birthday birthday;
private String job;
@ToString.Exclude
private String phoneNumber;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) // 1 대 1 relation을 지정함
@ToString.Exclude
private Block block;
}
*PersonService.java
package com.fastcampus.javaallinone.project3.mycontact.service;
import com.fastcampus.javaallinone.project3.mycontact.domain.Person;
import com.fastcampus.javaallinone.project3.mycontact.repository.PersonRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Slf4j
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List<Person> getPeopleExcludeBlocks(){
// List<Person> people = personRepository.findAll();
// return people.stream().filter(person -> person.getBlock() == null).collect(Collectors.toList());
//people 리스트 중에서 block 이 되지 않은 값만 리턴
return personRepository.findByBlockIsNull();
}
public List<Person> getPeopleByName(String name){
// List<Person> people = personRepository.findAll();
//
// return people.stream().filter(person -> person.getName().equals(name)).collect(Collectors.toList());
return personRepository.findByName(name);
}
@Transactional
public Person getPerson(Long id){
// Person person = personRepository.findById(id).get();
Person person = personRepository.findById(id).orElse(null);
// System.out.println("person : " + person);
log.info("person ; {}", person); //log출력을 제한할 수 있는 장점이 있어서 print보다 많이 쓴다.
return person;
}
@Transactional
public void put(Person person){
personRepository.save(person);
}
}
*MyContactApplication.java
package com.fastcampus.javaallinone.project3.mycontact;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MycontactApplication {
public static void main(String[] args) {
SpringApplication.run(MycontactApplication.class, args);
}
}
패스트캠퍼스 강의: https://bit.ly/3ilMbIO
반응형
'언어공부 > JAVA&SPRING' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 34회차 미션 (0) | 2020.09.12 |
---|---|
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 33회차 미션 (0) | 2020.09.11 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 31회차 미션 (0) | 2020.09.09 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 30회차 미션 (0) | 2020.09.08 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 29회차 미션 (0) | 2020.09.07 |
댓글