728x90
반응형

작성일자 : 2019.11.03

환경 : npm 6.12.0

 

 

1. create-react-app 설치

 

> npm -g install create-react-app 

 


2. Project 생성

 

> create-react-app "ProjectName"

 

# VSCode 내 터미널에서는 명령어 안먹힘 -> CMD 사용


3. Project 실행

 

> cd "PrjoectName"
> npm start

 

확인 

Port : 3000

 

 

 

 

728x90
반응형

'도구, 툴 > 세팅' 카테고리의 다른 글

[vue] vuetify 사용 설정  (1) 2019.07.21
SVN 저장소 설정  (0) 2018.07.21
GIT 저장소 설정  (0) 2018.07.15
node.js 설치  (0) 2018.06.10
VSCode 설치  (0) 2018.06.10
728x90
반응형

Cache 적용

 

작성일자 : 2019.09.28

환경 : Spring Boot 2.1.8

 

 

1. Cache 사용 설정

 

import org.springframework.cache.annotation.EnableCaching;

 

@SpringBootApplication
@EnableCaching
public class MybatistestApplication {
   public static void main(String[] args) {
      SpringApplication.run(MybatistestApplication.class, args);
   }
}

 

 

2. Cache 사용 대상 선언

 

  • @Cacheable: 캐시 채우기를 트리거합니다.

  • @CacheEvict: 캐시 제거를 트리거합니다.

  • @CachePut: 메소드 실행을 방해하지 않고 캐시를 업데이트합니다.

  • @Caching: 메소드에 적용 할 여러 캐시 조작을 재 그룹화합니다.

  • @CacheConfig: 클래스 수준에서 몇 가지 일반적인 캐시 관련 설정을 공유합니다.

 

import org.springframework.cache.annotation.Cacheable;

 

@Cacheable("CacheName")
public void method(){

   ... 

   ...

}

 

해당 설정 이후, 캐시 적용

 

 

3. 확인

 

*주의 : 같은 클래스 내의 캐시 적용 함수를 호출 시 캐시 기능 미적용 ( this.cacheMethod() 등 )

 

import org.springframework.cache.CacheManager;

 

public class MyClass {

        @RequestMapping("/cacheTest")
                public String cacheTest() {       
                      service.cacheMethod();  // Cache가 적용 된 함수 호출
                      return "test";
                }

}

 

@Cacheable("CacheName")
public String cacheMethod(){
         return "Test"
};

 

 

위와 같이 작성 후 cacheTest를 호출 하면 아래와 같이 진행

 

 

- 첫 접근 시

 

1. cacheTest 실행 

2. cacheMethod Cache 확인 ( 캐시 데이터 없음 )

3. cacheMethod 실행

4. cacheMethod 결과 값 캐싱

5. cacheMethod 결과 값 반환

5. cacheTest 결과 값 반환

 

 

- 이후 접근 시

 

1. cacheTest 실행 

2. cacheMethod Cache 확인 ( 캐시 데이터 존재 )

3. 캐시 데이터 반환 ( cacheMethod 미실행 )

 

 

캐싱 상황은 CacheManager를 통해 확인 가능

 

@Autowired 
CacheManager cacheManager;

 

 

첫 접근 시, 캐시 데이터 X

- Spring은 CacheManager로 ConcurrentMapCacheManager를 Default로 사용

 

 

이후 접근 시, 캐시 데이터 존재 확인

- 어노테이션 내 설정 아이디로 Key 생성 ( @Cacheable("CacheName") )

- 캐시 된 데이터 존재

 

 

728x90
반응형

'Java' 카테고리의 다른 글

Stream Example  (0) 2020.01.05
리스트 순환 중 아이템 삭제  (0) 2019.12.08
Spring Boot + MySQL 연동  (0) 2019.09.14
[spring boot] AOP 설정  (0) 2019.07.21
[Spring Boot-Vue] 프로젝트 빌드  (0) 2019.07.21
728x90
반응형

Spring Boot + MySQL 연동

 

작성일자 : 2019.09.14

환경 : Spring Boot 2.1 MySQL 5.7 + Gradle, MyBatis

 

 

1. 연동 

 

1.1 ) Dependency 추가

 

build.gradle

 

...

dependencies {

...

   compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2")
   compile("commons-dbcp:commons-dbcp:1.4")
   compile("mysql:mysql-connector-java:5.0.8")

...

}

 

 

1.2 ) Config

 

DBConfig.java

 

package com.example.demo;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
public class DBConfig {

 

   @Bean
   public DataSource dataSource() {
      BasicDataSource dataSource = new BasicDataSource();

     

      // DB 정보 ( 환경에 맞게 수정 필요 )
      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/rmsdb");  // jdbc:mysql://'domain':'port'/'DataBaseName'
      dataSource.setUsername("root"); // ID
      dataSource.setPassword("qweqweqwe"); // PW


      return dataSource;
   }

 

   @Bean
   public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
      SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
      sqlSessionFactory.setDataSource(dataSource);


      sqlSessionFactory.setMapperLocations(
         new PathMatchingResourcePatternResolver().getResources("classpath*:com/example/demo/*.xml")
      ); // Mapper 위치 설정


      return (SqlSessionFactory)sqlSessionFactory.getObject();
   }

   @Bean
   public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
      return new SqlSessionTemplate(sqlSessionFactory);
   }


}

 

++

Mybatis는 SqlSession이라는 자바 인터페이스를 이용

SqlSessionFactory에서 SqlSession를 생성

SqlSessionTemplate은 SqlSession을 구현하고 코드에서 SqlSession를 대체하는 역할

 

 

1.3 ) 연동 확인

 

Test Controller 생성 후 설정한 Bean 정보 출력

 

package com.example.demo;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {

   @Autowired
   DataSource dataSource;

   @Autowired
   SqlSessionFactory sqlSessionFactory;

   @Autowired
   SqlSessionTemplate sqlSessionTemplate;

   @RequestMapping("/check")
   public void test() throws SQLException {
      System.out.println(dataSource.getClass());
      System.out.println(sqlSessionFactory.getClass());
      System.out.println(sqlSessionTemplate.getClass());
      System.out.println(dataSource.getConnection());
   }
}

 

콘솔 확인

 

 

2. 기본 CRUD 세팅

 

MyBatis의 Mapper 연결 방식은

1. Mapper namespace를 직접 선언하여 연결하는 방식과

2. Mapper Interface를 활용하는 방식이 존재

 

해당 글에서는 Mapper namesapce를 직접 사용

 

 

TestDto.java

 

package com.example.demo;

 

public class TestDto {

 

        String id;

        String comment;

       

        public String getComment() {

               return comment;

        }

        public String getId() {

               return id;

        }

        public void setComment(String comment) {

               this.comment = comment;

        }

        public void setId(String id) {

               this.id = id;

        }

}

 

 

TestDao.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

<mapper namespace="com.example.demo.TestDao">

           <select id="selectList" resultType="com.example.demo.TestDto">

                     SELECT *

                     FROM

                                testtable

           </select>

          

           <select id="selectOne" parameterType="com.example.demo.TestDto" resultType="com.example.demo.TestDto">

                     SELECT *

                     FROM

                                testtable

                     WHERE

                                id = #{id}

           </select>

          

           <insert id="create" parameterType="com.example.demo.TestDto">

                     INSERT INTO testtable ()

                     VALUES (

                                #{id},

                                #{comment}

                     )

           </insert>

          

           <update id="update" parameterType="com.example.demo.TestDto">

                     UPDATE testtable

                     SET

                                comment = #{comment}

                     WHERE

                                id = #{id}

           </update>

          

           <delete id="delete" parameterType="com.example.demo.TestDto">

                     DELETE

                     FROM

                                testtable

                     WHERE

                                id = #{id}

           </delete>

          

</mapper>

 

SqlSessionFactory의 Mapper 설정 위치 아래에 생성

mapper에서의 namespace 및 id는 DAO에서 Parameter로 사용

 

 

TestDao.java

 

package com.example.demo;

 

import java.util.List;

 

import org.mybatis.spring.SqlSessionTemplate;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

 

@Repository("TestDao")

public class TestDao {

       

        @Autowired

        private SqlSessionTemplate sqlSessionTemplate;

       

        public List<TestDto> selectList(){

               return sqlSessionTemplate.selectList("com.example.demo.TestDao.selectList");

        };

 

        public TestDto selectOne(TestDto testDto){

               return sqlSessionTemplate.selectOne("com.example.demo.TestDao.selectOne",testDto);

        };

       

        public int create(TestDto testDto){

               return sqlSessionTemplate.insert("com.example.demo.TestDao.create",testDto);

        };

       

        public int update(TestDto testDto){

               return sqlSessionTemplate.update("com.example.demo.TestDao.update",testDto);

        };

       

        public int delete(TestDto testDto){

               return sqlSessionTemplate.delete("com.example.demo.TestDao.delete",testDto);

        };

}

 

 

 

TestController.java

 

package com.example.demo;

 

import java.sql.SQLException;

 

import javax.sql.DataSource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionTemplate;

import org.springframework.beans.factory.annotation.Autowired;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller

public class TestController {

       

        @Autowired

        DataSource dataSource;

 

        @Autowired

        SqlSessionFactory sqlSessionFactory;

       

        @Autowired

        SqlSessionTemplate sqlSessionTemplate;

       

 

        @Autowired

        TestDao testDao;

       

        @RequestMapping("/check")

        public String test() throws SQLException {

               System.out.println(dataSource.getClass());

               System.out.println(sqlSessionFactory.getClass());

               System.out.println(sqlSessionTemplate.getClass());

               System.out.println(dataSource.getConnection());

               return "test";

        }

       

        @RequestMapping("/1")

        public String create() {

               TestDto testDto = new TestDto();

               testDto.setId("1");

               testDto.setComment("Comment");

               testDao.create(testDto);

               return "create";

        }

       

        @RequestMapping("/2")

        public String read() {

               TestDto testDto = new TestDto();

               testDto.setId("1");

               System.out.println(testDao.selectList());

               System.out.println(testDao.selectOne(testDto));

               return "read";

        }

       

        @RequestMapping("/3")

        public String update() {

               TestDto testDto = new TestDto();

               testDto.setId("1");

               testDto.setComment("update");

               testDao.update(testDto);

               return "update";

        }

       

        @RequestMapping("/4")

        public String delete() {

               TestDto testDto = new TestDto();

               testDto.setId("1");

               testDao.delete(testDto);

               return "delete";

        }

}

 

 

 

 

DB Schema

 

CREATE TABLE `testtable` (
  `id` varchar(45) NOT NULL,
  `comment` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

 

 

---------

 

위 설정 후 Controller로의 URL 접근을 통해 CRUD 기능 동작 확인 가능

 

1. Create

 

 

 

2. Read

 

각각 List와 Obejct 형태

 

 

3. Update

 

 

4. Delete

 

 

Project 구조

 

 

-----------

++

Mapper Interface 활용 방식

 

in java

@Mapper
public interface MapperInterface {
   List selectList();
   TestDto selectOne(TestDto testDto);
   int create(TestDto testDto);
   int update(TestDto testDto);
   int delete(TestDto testDto);
}

 

 

In .xml

<mapper namespace="com.example.demo.MapperInterface">

   ...

</mapper>

이 경우 SqlSessionTemplate, SqlSessionFactory 설정은 필요 X

 

++

xml 없이 Mapper Interface에 SQL을 설정하는 방법도 있다

ex)

 

@Mapper
public interface MapperAnnotation {
   @Select("SELECT * FROM testtable")
   List selectList();

   @Select("SELECT * FROM testtable WHERE id = #{id}")
   TestDto selectOne(TestDto testDto);

   @Insert("INSERT INTO testtable () VALUES (#{id}, #{comment})")
   int create(TestDto testDto);

   @Update("UPDATE testtable SET comment = #{comment} WHERE id = #{id}")
   int update(TestDto testDto);

   @Delete("DELETE FROM testtable WHERE id = #{id}")
   int delete(TestDto testDto);
}

728x90
반응형

'Java' 카테고리의 다른 글

리스트 순환 중 아이템 삭제  (0) 2019.12.08
[Spring] Cache 적용  (0) 2019.09.28
[spring boot] AOP 설정  (0) 2019.07.21
[Spring Boot-Vue] 프로젝트 빌드  (0) 2019.07.21
[Spring Boot] JPA(Hibernate) 적용  (0) 2019.07.06

+ Recent posts