spring jpa namedQuery 직접 호출하기

Test.java에서 처럼 EntityManager를 이용하여 orm.xml에 정의한 NamedQuery를 바로 실행 할 수 있다.. repository를 이용하여 호출하면 getResultList로만 실행되는 것 같다. update 반영된 Row수를 알기 위해 아래와 같이 호출 했다. Test.java 1 2 3 4 5 6 @PersistenceContext private EntityManager em; public void test() { int cnt = em.createNamedQuery("Order.clearOrder").executeUpdate(); logger.info("Order.clearOrder updated={}", cnt); } @PersistenceContext private EntityManager em; 에서.. @PersistenceContext @Autowired 둘다 작동 하는것 같다. 차이는 아직 잘 모르겠다. ...

November 13, 2015 · 1 min · 페이퍼

spring redis 연동

pom.xml 에 아래 추가. 1 2 3 4 5 6 7 8 9 10 <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.1.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> 버전을 잘 맞춰야 한다. 안그러면 몇몇 class가 없어서 오류가 발생해요. context-redis.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:usePool="true" p:hostName="172.xxx.xxx.xxx" p:port="6379" /> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="jedisConnFactory" /> </beans> 6379가 redis기본 포트이다. 설치시 변경 가능하다. ...

November 10, 2015 · 2 min · 페이퍼

spring + sitemesh 웹사이트 구축

sitemesh를 설정을 해보겠습니다. pom.xml 1 2 3 4 5 <dependency> <groupId>opensymphony</groupId> <artifactId>sitemesh</artifactId> <version>2.4.2</version> </dependency> WEB-INF/web.xml 에 아래 추가. 1 2 3 4 5 6 7 8 <filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> WEB-INF/sitemesh.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <?xml version="1.0" encoding="UTF-8"?> <sitemesh> <property name="decorators-file" value="/WEB-INF/decorators.xml" /> <excludes file="${decorators-file}" /> <page-parsers> <parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" /> <parser content-type="text/html;charset=UTF-8" class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" /> </page-parsers> <decorator-mappers> <mapper class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper"> <param name="decorator" value="printable" /> <param name="parameter.name" value="printable" /> <param name="parameter.value" value="true" /> </mapper> <mapper class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper" > <param name="property" value="meta.decorator" /> </mapper> <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper"> <param name="config" value="${decorators-file}" /> </mapper> </decorator-mappers> </sitemesh> sitemesh.xml파일은 수정할 부분이 거의 없습니다 (decorators.xml파일 경로) ...

October 28, 2015 · 3 min · 페이퍼

spring jpa 저장

jpa에서는 저장시 repository.save 함수를 이용하여 저장합니다 Member class처럼 @OneToMany나 @ManyToOne 필드들을 함께 저장 할 수 있습니다. Member.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Entity @Table(name = "tb_member") public class Member { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "member_seq") public Integer memberSeq; @Column public String nickname; @Expose @OneToMany( targetEntity = MemberInter.class , cascade = CascadeType.ALL , fetch = FetchType.EAGER , mappedBy = "memberSeq") public List<MemberInter> memberInterList; } MemberInter.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Entity @Table(name="tb_member_inter") @IdClass(value = MemberInterPk.class) public class MemberInter { @Id @Column(name = "member_seq") public Integer memberSeq; @Id @Column(name = "inter_seq") public Integer interSeq; @ManyToOne( targetEntity = Inter.class ,cascade = CascadeType.ALL ,fetch = FetchType.LAZY ,optional = false ) @JoinColumn(name = "inter_seq", referencedColumnName = "inter_seq" , insertable = false, updatable = false) public Inter inter; } @JoinColumn에 insertable, updateable을 추가 하여 false 했습니다 ...

October 21, 2015 · 2 min · 페이퍼

spring jpa의 @NamedQuery, @NamedNativeQuery 연습

jpa에서.. repository를 이용하여 findAll이나.. findOneBy…. 시리즈를 써서 데이타를 조회 할수 있지만 아래와 같이 특정 쿼리를 직접 입력하여 이용도 가능합니다. /classes/META-INF/orm.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 <?xml version="1.0" encoding="UTF-8"?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" version="2.0"> <named-query name="Inter.findByAlal2"> <query>select i from Inter i where i.internameko = ?1</query> </named-query> <named-native-query name="Inter.findByAlal" result-class="sample.jpa.Inter"> <query>select a.inter_seq, a.inter_name_ko, a.inter_name_en from tb_inter a where a.inter_name_ko = ?</query> </named-native-query> </entity-mappings> 또는.. 아래와 같이 Entity 클래스에 선언해도 됩니다 ...

October 8, 2015 · 1 min · 페이퍼

spring jpa 조회 연습

entity 작업에 조회까지.. 테스트 해봤습니다. 테이블의 관계가 아래와 같을때 상황 1 tb_member -< tb_member_inter >- tb_inter 조회 조건 Member를 가져오면.. member의 이미지들과… inter의 목록을 함께 가져오도록 inter의 상세 정보는 tb_inter에 있음 (가져올때 조인해서..) 아래 class들 간략 설명 MemberInter의 PK가 두개이므로. 위와 같이 클래스를 하나 만들어서 @IdClass를 지정해야 함 @Expose 는 Gson관련하여 화면에 뿌릴 필드를 정하는 옵션입니다. jpa와는 무관합니다. MemberInter.class에서 많이 헷갈렸습니다. (@ManyToOne) @JoinColumn을 추가로.. 써야 합니다. optional을 true로 하면 join시 outer join을 합니다. (false는 inner join) FetchType ...

October 7, 2015 · 2 min · 페이퍼

spring jpa 설정 및 테스트 (maven 설정)

거의 대부분 mybatis 를 이용하여 개발을 하는데.. JPA가 대세라고 해서 가벼운 프로젝트에 연동을 해봤습니다. 1. 라이브러리 import…. maven pom.xml 1 2 3 4 5 6 7 8 9 10 <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.9.0.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.8.Final</version> </dependency> 2. Entity class를 만들어 줍니다. 참고로 SerializedName, Expose는 jpa와 직접 관련은 없습니다.. (개체를 그대로 JsonView 할때 사용) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import javax.persistence.*; @Entity @Table(name="tb_notice") public class Notice { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "notice_id") @SerializedName(value = "notice_id") @Expose private Integer noticeId; @Column(name="title", nullable = false) @Expose private String title; @Column(name="content", nullable = false) @Expose private String content; @Column(name="reg_date", nullable = false) @SerializedName(value = "reg_date") @Expose private String regDate; @Column(name="del_yn", nullable = false) @Expose(serialize = false, deserialize = false) private String delYn; public Integer getNoticeId() { return noticeId; } public void setNoticeId(Integer noticeId) { this.noticeId = noticeId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getDelYn() { return delYn; } public void setDelYn(String delYn) { this.delYn = delYn; } } 3. repository 를 만들어줍니다. (아무것도 없어도 된다) 1 2 3 public interface NoticeRepository extends JpaRepository<Notice, Integer> { } 4. context-jpa.xml 설정합니다. txManager2인 이유는 기존에 mybatis에 영향을 주지 않기 위해서입니다. , mybatis를 한번에 다 걷어낼 자신이 없… 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <!-- Configure the transaction manager bean --> <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="txManager2"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:advice id="txAdvice2" transaction-manager="txManager2"> <tx:attributes> <tx:method name="*" rollback-for="Exception" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* sample..service..*.sr*(..))" id="requiredTx2" /> <aop:advisor advice-ref="txAdvice2" pointcut-ref="requiredTx2" /> </aop:config> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" id="hibernateJpaVendorAdapter"> <property name="showSql" value="true" /> </bean> <!-- Configure the entity manager factory bean --> <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" /> <property name="packagesToScan" value="sample.app" /> </bean> <jpa:repositories base-package="sample.app" transaction-manager-ref="txManager2" /> </beans> 5. 사용 예제 1 2 3 4 5 6 7 8 9 10 11 12 @Service public class NoticeService extends ServiceBase { private static final Logger logger = LoggerFactory.getLogger(NoticeService.class); @Autowired private NoticeRepository noticeRepository; public void srXX(RequestData req, ResponseData res) throws Exception { List<Notice> list = noticeRepository.findAll(); res.put("notice_list", list); } } 인터넷상에 자료가 많아서 설정은 어렵지 않았습니다. ...

October 5, 2015 · 3 min · 페이퍼

spring batch 사용

최근에 spring-batch를 사용해 봤는데.. 결과는 성공적 특히 트랜잭션commit size와 read size를 따로 지정할 수 있다는게 좋은것 같다. 쿼리나 기타 로직보다 아래 설정이 중요한 듯 하여 아래 설정을 기록으로 남긴다. job에 대해서 요약하면 reader에서 데이타를 읽어서 process 에서 처리 하고 writer로 결과를 기록 한다. 물론 위 설정 외에 각 시작 구간마다 이벤트를 받아 처리 할 수 있는 listener 같은 것도 제공한다. reader, writer는 커스텀 하지 않고 mybatis에서 기본으로 제공하는 걸 이용했다. 참고) https://mybatis.github.io/spring/ko/batch.html ...

August 27, 2015 · 1 min · 페이퍼

하둡 스프링 연동 테스트2 - hadoop 2.6.x with spring 4.0 (MapReduce WordCount example)

context-hadoop.xml에 아래 내용 추가. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <hdp:configuration id="hdConf"> fs.default.name=hdfs://localhost:9000 </hdp:configuration> <hdp:job id="wordCountJob" input-path="/input/" output-path="/output/" configuration-ref="hdConf" mapper="delim.app.service.WordCount$TokenizerMapper" reducer="delim.app.service.WordCount$IntSumReducer" > </hdp:job> <hdp:job-runner id="wordCountJobRunner" job-ref="wordCountJob" run-at-startup="false"> </hdp:job-runner> WordCount.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.StringTokenizer; public class WordCount { private static final Logger logger = LoggerFactory.getLogger(WordCount.class); public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { logger.info("map key={}, value={}", key, value); StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); @Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { logger.info("reduce key={}", key); int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } } Test.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Autowired private org.apache.hadoop.conf.Configuration hdConf; @Autowired private JobRunner wordCountJobRunner; @Before public void beforeCopyFile() throws IOException { String file = "/Users/paper/Desktop/4/14/debug.2015-04-09.log"; Path srcFilePath = new Path(file); Path dstFilePath = new Path("/input/debug.2015-04-09.log"); FileSystem hdfs = FileSystem.get(dstFilePath.toUri(), hdConf); hdfs.copyFromLocalFile(false, true, srcFilePath, dstFilePath); hdfs.delete(new Path("/output/"), true); } @Test public void testRunJob() throws Exception { wordCountJobRunner.call(); } Before를 통하여 로컬에 있는 debug.log 파일을 hdfs에 카피 해놓는다. Job을 실행한다. 실행하면 debug.log 파일을 line단위로 읽어들이는걸 확인 할 수 있다. (WordCount$TokenizerMapper)

April 15, 2015 · 2 min · 페이퍼

하둡 스프링 연동 테스트 - hadoop 2.6.x with spring 4.0

Hadoop 설치 및 설정은 아래와 같이 (osx 요세미티.) https://hadoop.apache.org/releases.html#Download ( 2.6.x 버전 ) 설치는 아래 블로그 보고 함 http://iamhereweare.blogspot.kr/2014/05/hadoop.html pom.xml 에 아래 dependency 추가. 1 2 3 4 5 <dependency> <groupid>org.springframework.data</groupId> <artifactid>spring-data-hadoop</artifactId> <version>2.1.1.RELEASE</version> </dependency> context-hadoop.xml spring 설정에 파일 추가 1 2 3 4 5 6 7 8 9 10 11 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hdp="http://www.springframework.org/schema/hadoop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd"> <hdp:configuration id="hdConf"> fs.default.name=hdfs://localhost:9000 </hdp:configuration> </beans> 아래와 같이 test코드 작성. ...

April 12, 2015 · 2 min · 페이퍼