TIL - 19.12.30

노요셉·2019년 12월 30일
0

java stream

Stream은 자바 8부터 추가된 기능으로 "컬렉션, 배열등의 저장 요소를 하나씩 참조하며 함수형 인터페이스(람다식)를 적용하며 반복적으로 처리할 수 있도록 해주는 기능"이다.

@GetMapping("/v2/product")
    public Result findProduct(){

        List<Product> findProducts = productService.findProducts();

        List<ProductDto> collect = findProducts.stream()
                .map(p -> new ProductDto(p.getProduct_id(),
                        p.getProduct_thumbnails(),
                        p.getProduct_name(),
                        p.getProduct_category(),
                        p.getProduct_origin(),
                        p.getProduct_status()))
                .collect(Collectors.toList());
        System.out.println(collect.toString());
        return new Result(collect);

    }

    static class Result<T>{
        private T data;

        public Result(T data) {
            this.data = data;
        }

        public T getData() {
            return data;
        }
    }

    static class ProductDto{
        private Long productId;
        private String thumbnails;
        private String productName;
        private String productCategory;
        private String productOrigin;
        private String status;

        public ProductDto(Long productId, String thumbnails, String productName, String productCategory, String productOrigin, String status) {
            this.productId = productId;
            this.thumbnails = thumbnails;
            this.productName = productName;
            this.productCategory = productCategory;
            this.productOrigin = productOrigin;
            this.status = status;
        }
    }

출처: https://jeong-pro.tistory.com/165 [기본기를 쌓는 정아마추어 코딩블로그]

에러

No serializer found for class com.example.demo.api.ProductAPIController$ProductDto and no properties discovered to create BeanSerializer

해결책 : DTO의 Getter를 생성해줘요.

DTO, DAO

DAO(Data Access Object)는 DB를 사용해 데이터를 조화하거나 조작하는 기능을 전담하도록 만든 오브젝트를 말한다.

DTO(Data Transfer Object)는 VO(Value Object)로 바꿔 말할 수 있는데
계층간 데이터 교환을 위한 자바빈즈를 말한다. 여기서 말하는 계층간의
컨트롤러, 뷰, 비즈니스 계층, 퍼시스턴스 계층을 말하며 각 계층간 데이터 교환을
위한 객체를 DTO 또는 VO라고 부른다.

자바스크립트에서 객체를 console.log()로 찍을때 [Object object] 라고 나온다면

JSON.stringify(obj)를 통해 JSON 형태로 확인할 수 있습니다.
https://hiworldbye.tistory.com/48

es6에서 사용했던 문법들과 유사한 문법들이 자바 8 이후로 생겨난거 같습니다.

map, filter는 es6에서 사용했기 때문에 익숙한데,
collect는 뭔지 모르겠습니다.
https://www.mkyong.com/java8/java-8-streams-map-examples/

스프링 부트에서 datasource 설정하기

xml 설정방식이 아닌 Spring boot 애플리케이션에서 Java Config를 통해 DataSource를 설정하는 방법을 알아보도록 하겠습니다.

Spring Boot의 @EnableAutoConfiguration 어노테이션을 통해 DataSource 와 JdbcTemplate에 대한 Bean을 별도로 등록하지 않아도 되는데, 그렇다면 속성값을 어떠한 방식으로 설정할수 있을까요?

DataSource 의 설정은 application.properties 파일내에서 spring.datasource.* 와 같은 패턴으로 설정이 가능하다. application.properties에서 DataSource 설정하는 방식을 예를들어 보겠다,

application.properties

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Drive

https://www.holaxprogramming.com/2015/10/16/spring-boot-with-jdbc/

ResultSet이란

데이터베이스에 쿼리를 수행함으로써 생성된 결과값들의 집합입니다.
getString("컬럼명") 또는 getLong("컬럼명") 등을 통해 조회한 값들을 읽을 수 있습니다.

https://docs.oracle.com/en/java/javase/13/docs/api/java.sql/java/sql/ResultSet.html

spring-boot개발시 Setter로 DI할까요? Constructor DI를 할까요?

기본 생성자 관련 : 기본 생성자, 여러 생성자가있을 때 Autowired 주석이있는 생성자 또는 Autowired 주석이 있거나없는 클래스에 하나의 생성자 만 필요합니다.

출처: https://erea.tistory.com/10 [erea]

spring-boot 개발시 로그찍고 싶어요.

application.properties에
logging.level.root=DEBUG 추가해줍니다.

DTO

equals, hashCode 생성하기

왠만하면 자동으로 생성해주는 기능을 써야합니다. 오타날 수도 있으니까요.
intellij 에서는 cmd + n 하면 constructor, getter, setter등등이 나옵니다.
거기서 equals를 선택해줍니다.

equals, hashCode를 오버라이딩 함으로써 collections을 사용할때 정상적으로 동작합니다.

Address address1 = new Address("city","street","10000");
Address address2 = new Address("city","street","10000");
System.out.println(address1.equals(address2))); 
//false

equals의 기본연산 == 비교

MapSqlParameterSource

db에 insert하고 id를 리턴하고 싶어요.

https://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/key-holder.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html#update-java.lang.String-org.springframework.jdbc.core.namedparam.SqlParameterSource-org.springframework.jdbc.support.KeyHolder-

		MapSqlParameterSource parameters = new MapSqlParameterSource();
		parameters.addValue("node_id", e.getKey());
		parameters.addValue("local_size", e.getValue());
		batchArgs.add(parameters);

https://www.programcreek.com/java-api-examples/?class=org.springframework.jdbc.core.namedparam.MapSqlParameterSource&method=addValue

GeneratedKeyHolder 를 썼는데 key가 여러개래요.

KeyHolder keyHolder = new GeneratedKeyHolder();
org.springframework.dao.InvalidDataAccessApiUsageException: The getKey method should only be used when a single key is returned. The current key entry contains multiple keys:

저같은 경우는 product_id, timestamp가 getKey()를 반환해서 product_id를 리턴했습니다.

            jdbcTemplate.update(query, params, keyHolder, new String[]{"product_id"});
            return keyHolder.getKey().longValue();

jdbctemplate보다 파라미터에서 가독성이 나은

namedjdbctemplate를 사용하였습니다.
https://blog.outsider.ne.kr/882

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html

profile
서로 아는 것들을 공유해요~

0개의 댓글