본문 바로가기
Back-end/Spring

[JPA] 사용해보기

by JiGyeong 2016. 5. 4.

간단하게 JPA실습을 해보자



1. 메이븐 프로젝트로 바꾼뒤에

pom.xml에 아래 디펜던시들과 레파지토리를 추가해준다.




2. rootContext와 applicationContext를 Spring Bean Configuration File로 만들어준다.



rootJPAContext.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
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
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
 
    <bean id="dataSource"
            class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>    
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="username" value="SPRING"/>
        <property name="password" value="spring"/>
    </bean>
    
    
 
    
    <!-- JPA  공급자 설정-->
    <bean id="hibernateJpaVendorAdaptor"
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <!-- 자동 생성되는 SQL문을 보여주는 역할인듯 -->
        <property name="showSql" value="true"/>
    </bean>
    
    <!-- 캐시(영속성 컨테이너)에 접근할 수 있는 EntityManager 생성 -->
    <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdaptor"/>
        <property name="packagesToScan" value="com.ktds.jgbaek"/>
    </bean>
    
    <!-- JPA 전용 TransactionManager 생성 -->
    <bean id="txManager"
            class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>        
    </bean>
    
    
    <!-- JPA Repository 자동 탬색 경로 설정 -->
    <jpa:repositories base-package="com.ktds.jgbaek"
                        transaction-manager-ref="txManager"/>
    <!-- Transaction Advice 설정 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" rollback-for="RuntimeException"/>
        </tx:attributes>
    </tx:advice>
    
    <!--  Transanction AOP(Proxy) 설정 -->
    <aop:config>
        <aop:pointcut id="requiredTx"
                        expression="execution(* com.ktds.jgbaek..service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="requiredTx"/>
    </aop:config>        
</beans>
 
cs


applicationContext.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
29
30
31
32
33
<?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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <mvc:annotation-driven/>
    <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"></property>        
    </bean>
    
    <bean id="jpaBiz"
            class="com.ktds.jgbaek.biz.impl.JPABizImpl">
        <property name="jpaRepository" ref="jpaRepository"/>
    </bean>
    
    <bean id="jpaService"
            class="com.ktds.jgbaek.service.impl.JPAServiceImpl">
        <property name="jpaBiz" ref="jpaBiz"/>
    </bean>
    
    <bean id="jpaController"
            class="com.ktds.jgbaek.web.JPAController">
        <property name="jpaService" ref="jpaService"/>
    </bean>
    
</beans>
 
 
 
cs




3. vo대신 domain/ dao 대신 repository 로 biz, domain, repository, service, web을 만든다.



JPA.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
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.ktds.jgbaek.domain;
 
import java.util.List;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
 
@Entity
@Table(name="JPA")
public class JPA {
    
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", nullable=false)
    private int id;
    
    @Column(name="subject", nullable=true)
    private String subject;
    
    @Column(name="description", nullable=true)
    private String description;
    
    @OneToMany(mappedBy="jpa", fetch=FetchType.LAZY)
    private List<JPA2> jpa2;
    
 
    public List<JPA2> getJpa2() {
        return jpa2;
    }
    public void setJpa2(List<JPA2> jpa2) {
        this.jpa2 = jpa2;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
 
}
 
 
 
cs




JPABizImpl.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
50
51
52
53
package com.ktds.jgbaek.biz.impl;
 
import java.util.ArrayList;
import java.util.List;
 
import com.ktds.jgbaek.biz.JPABiz;
import com.ktds.jgbaek.domain.JPA;
import com.ktds.jgbaek.domain.JPA2;
import com.ktds.jgbaek.repository.JPARepository;
 
public class JPABizImpl implements JPABiz{
 
    private JPARepository jpaRepository;
    
    public void setJpaRepository(JPARepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }
 
    @Override
    public JPA insertData() {
        JPA jpa= new JPA();
        jpa.setSubject("JPA Test");
        jpa.setDescription("JPA Desctiprion");
        
        JPA2 jpa2 = new JPA2();
        jpa2.setMemo("반갑습니다..");
        
        List<JPA2> jpa2List = new ArrayList<JPA2>();
        jpa2List.add(jpa2);
        
        jpa.setJpa2(jpa2List);
        
        jpaRepository.save(jpa);
        
        System.out.println(jpa.getSubject());
        System.out.println(jpa.getDescription());
        System.out.println(jpa.getId());
        
        return jpa;
    }
 
    @Override
    public JPA updateData(JPA jpa) {
        jpaRepository.save(jpa);
        
        JPA jpas = jpaRepository.findOne(7);
        return jpa;
    }
 
}
 
 
 
cs

JPARepository.java
신기하게 아무것도 구현하지 않았는데 자동으로 쿼리가 만들어진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.ktds.jgbaek.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
import com.ktds.jgbaek.domain.JPA;
 
@Repository("jpaRepository")
public interface JPARepository extends JpaRepository<JPA, Integer>{
 
}
 
 
 




JPAServiceImpl.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
package com.ktds.jgbaek.service.impl;
 
import com.ktds.jgbaek.biz.JPABiz;
import com.ktds.jgbaek.domain.JPA;
import com.ktds.jgbaek.service.JPAService;
 
public class JPAServiceImpl implements JPAService{
 
    private JPABiz jpaBiz;
    
    public void setJpaBiz(JPABiz jpaBiz) {
        this.jpaBiz = jpaBiz;
    }
 
    @Override
    public void insertData() {
        JPA jpa = jpaBiz.insertData();
        
        jpa.setSubject("수정합니다...");
        jpaBiz.updateData(jpa);
    }
    
}
 
 
cs



결과창에 자동으로 쿼리가 만들어진다.

만약 안된다면 직접 HIBERNATE_SEQUENCE를 만들어주면 된다.

테이블은 JPA테이블의 ID, SUBJECT, DESCRIPTION 칼럼을 만들어줬다.





'Back-end > Spring' 카테고리의 다른 글

[Spring] 웹소켓 js파일  (0) 2017.06.05
[Spring] 공부문제  (2) 2016.05.31
[JPA] JPA에 관해..  (0) 2016.05.04
[HTML] 자동완성 기능 만들기  (0) 2016.05.03
[HTML] 서버돌리지 않고 창 띄우기  (0) 2016.05.02