MyBatis Application Project 작업순서

Posted 2019. 7. 9. 11:24

java application project에서 테스트를 위한 작업순서(in Maven 프로젝트)

 

1. pom.xml 추가

  1.1 mybatis 기본 dependency 추가 

  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.1</version>
	</dependency>

 

  1.2 config.xml 설정파일 관련 dependency 추가

<!-- https://mvnrepository.com/artifact/commons-configuration/commons-configuration -->
	<dependency>
	    <groupId>commons-configuration</groupId>
	    <artifactId>commons-configuration</artifactId>
	    <version>1.10</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
	<dependency>
	    <groupId>commons-collections</groupId>
	    <artifactId>commons-collections</artifactId>
	    <version>3.2.1</version>
	</dependency>

  1.3 Config.java, ConnectionFactory.java 생성   

-- Config.java --

public class Config {
	private static Configuration configuration;
	 
    static {
        try {
        	URL url = Config.class.getClassLoader().getResource("config/database.xml");
            if (configuration == null) {
				configuration = new XMLConfiguration(url);
            } else {
            	System.out.println("return configuration from Memory...");
            }
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }   
    public static Configuration getConfiguration() {
        return configuration;
    }
}

--  ConnectionFactory.java -----

public class MyBatisConnectionFactory {
	private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            final String resource = "config/mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            if (sqlSessionFactory == null) {
            	Configuration conf = MyConfig.getConfiguration();    			
    			Properties props = new Properties();    			
    			props.setProperty("driver",	 	conf.getString("jdbc.driver","oracle.jdbc.driver.OracleDriver"));
    			props.setProperty("url", 		conf.getString("jdbc.url","jdbc:oracle:thin:@127.0.0.1:1521:orcl"));
    			props.setProperty("username", 	conf.getString("jdbc.username","test2018"));
    			props.setProperty("password", 	conf.getString("jdbc.password","test2018"));
    			
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, props);
            }
        } catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        } catch (IOException iOException) {
            iOException.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

 

2. TestMain.java 테스트 (Transaction 처리 포함 테스트)

  ...중략...
  
	public static void main(String[] args) {

		SqlSession sqlSession = null;
		try {
			sqlSession = MyBatisConnectionFactory.getSqlSessionFactory().openSession(false);

			//Mapper 사용하는 방법
			TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
			List<Map<String, Object>> progrmList = testMapper.getProgrmList();
			
			//Sqlsession을 사용하는 방법
			List<Map<String, Object>> progrmList = (List<Map<String,Object>>)sqlSession.selectList("getProgrmList");
			
			
			for (Iterator iterator = progrmList.iterator(); iterator.hasNext();) {
				Map<String, Object> map = (Map<String, Object>) iterator.next();
				System.out.println(map);				
			}
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("id", "test8");
			param.put("name", "test8 name");
			param.put("age", 88);
			
			testMapper.insertTest(param);
			
			Map<String, Object> param2 = new HashMap<String, Object>();
			param2.put("id", "test5");
			param2.put("name", "test5 update name");
			param2.put("age", 28);
			testMapper.updateTest(param2);
			
			// 커밋
			sqlSession.commit();
		} catch (Exception e) {
			// 롤백
			sqlSession.rollback();
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}

 

 

 

 



SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");

를 자주 사용합니다.

 

String today = sdf.format(Calendar.getInstance().getTime());

 

문자열로 변환해서 사용할때 유용합니다. 하지만 위의 코드에는 오묘한 버그가 숨어있습니다.

프로젝트 말미에 급하게 추가하면서 테스트하고 바로 적용하여 오픈.

 

하지만 12월 28일이 되어서야 위의 코드에 문제가 있음이 발각(?) 되었습니다.

 

분명 어제까지 잘 되던 로직이 12월 28일이 되면서 오류를 내뱉기 시작했습니다. 1년이나 빠른 날짜를 가져오는 것이었습니다.

 

원인은 패턴문자열 오류때문이었습니다.

 

"YYYYMMdd" vs "yyyyMMdd"

 

연도를 나타내는 yyyy를 소문자가 아닌 대문자로 사용할 경우 미묘한 오류가 발생합니다.

 

자칫 악용하면 연말에만 발생하는 버그를 만들수도 있겠네요.

 



간만에 포스팅합니다.


모바일에서 리사이징 없이 업로드 된 이미지의 경우 너무 사이즈가 크다보니 이를 그대로 서비스하다보면 보는 사용자가 제공하는 서버나 둘다 필요없는 시간낭비, 트래픽 낭비를 초래합니다.


그동안 jdk 자체제공된 라이브러리를 이용하여 구현했었는데, 구글링을 통해 좋은 유틸 jar를 발견하게 되었습니다.


해당 jar 파일입니다. 현재 4.2버전을 제공하고 있어 이를 다운받아 개발에 사용했습니다.


imgscalr-lib-4.2.jar


maven을 사용하려면 다음과 같이 추가합니다.

        <dependency>

<groupId>org.imgscalr</groupId>

<artifactId>imgscalr-lib</artifactId>

<version>4.2</version>

</dependency>


기본적인 사용법은 간단합니다.

프로젝트에서 사용한 방법만 간단히 예제코드와 함께 소개합니다.


업로드를 받는 controller 메소드 일부분입니다.

@ResponseBody

@SuppressWarnings("unchecked")

@RequestMapping(value="/api/apchart/upload",method= RequestMethod.POST)

public ModelAndView  imageUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("upload_media") MultipartFile multipart ){

 .....  중략 .....


          String orgFilePath = UPLOAD_ABS_PATH + newFileName + "_org_"+file.getOriginalFilename();

  File orgFile = new File(orgFilePath);

  file.transferTo(orgFile);

  

           //Image Crop & Resize...

           FileUtils.imageResize(orgFilePath, filePath, "jpg");

           orgFile.delete();


  ..... 중략 .....


실제 Crop & Resize를 담당하는 FileUtils.imageResize 메소드 부분입니다.

public static void imageResize(String orgFilePath, String targetFilePath, String imageType) throws Exception{


BufferedImage originalImage = ImageIO.read(new File(orgFilePath));

int imgwidth = Math.min(originalImage.getHeight(),  originalImage.getWidth());

int imgheight = imgwidth;

BufferedImage scaledImage = Scalr.crop(originalImage, (originalImage.getWidth() - imgwidth)/2, (originalImage.getHeight() - imgheight)/2, imgwidth, imgheight, null);

BufferedImage resizedImage = Scalr.resize(scaledImage, 300, 300, null);

ImageIO.write(resizedImage, imageType, new File(targetFilePath));

}


위의 메소드는 이미지 센터를 중심으로 정사각형으로 crop 하고 300pixel 기준으로 리사이징하도록 하였습니다.


위의 과정을 거친 이미지는 다음과 같이 변경됩니다.


<변경전 원본이미지> - 원본이미지가 너무 커서 블로그상에서 resize만 처리하여 업로드



<정사각형 crop 후의 이미지>




<300pixel로 resize 된 이미지>



자세한 사용법은 다음의 url을 참고하세요.



http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/

















« PREV : 1 : 2 : 3 : NEXT »