관리 메뉴

취미개발 블로그와 마음수양

Google App engine 스프링 + JPA 연동 (앱엔진 스프링 JPA) 본문

FrameWork_ETC/Spring

Google App engine 스프링 + JPA 연동 (앱엔진 스프링 JPA)

아라한사 2014. 12. 15. 11:39

깃허브 주소 : https://github.com/arahansa/gaeSpring


슬라이드 쉐어 주소 : http://www.slideshare.net/meadunhansa/datajpa


이곳은 피피티가 복붙이 안되기 때문에 복붙을 위하여 막 적는 곳이다. 


삽질을 하면서 실시간으로 피피티를 만들다 보니 피피티가 좀 깔끔하지가 않다. ㅡㅡ;;

이해해주시길 바란다. 




그 다음으로 어디보자..소스들을 적어보자면..


자주쓰는 메이븐 명령어 : 

실행파일들 깨끗하게 mvn clean

이클립스로 만들어주는 것 mvn eclipse:eclipse 

로컬에서 실행시 쓰는 명령어 : mvn appengine:devserver 

서버로 올릴때 명령어 mvn appengine:update



앱엔진 사이트 

아...피피티에서 복붙을 그대로 하니 그대로 나온다 ㅡㅡ;; 


https://cloud.google.com/appengine/
그 다음에 이클립스 플러그인들 주소 : 

https://cloud.google.com/appengine/docs/java/tools/eclipse




자기 앱 확인 사이트!

https://appengine.google.com/



메이븐 빌드 적용 부분..

메이븐명령어 (참고로 그냥 처음에 mvn archetype:generate 를 해주고 일일이 정해줘도 된다)  

mvn archetype:generate -Dappengine-version=1.9.17 -Dapplication-id=앱아이디 -Dfilter=com.google.appengine.archetypes:


이거 해준다음에 아마 mvn eclipse:eclipse 해줬었지 아마...

=========================================

스프링 연동.


스프링 연동에서 pom.xml

1
2
3
4
5
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
cs


spring 컨트롤러

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.example.domain.TestClass;
import com.example.repository.TestRespository;
 
@Controller
public class TestController {
 
    @Autowired
    TestRespository repository;
    
    @RequestMapping("/spring")
    String index(){
        return "index";
    }
}
cs


dispatcher Servlet (web-app 폴더 안에 meta-inf\spring 폴더안에 넣었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
    <context:annotation-config />
    <mvc:annotation-driven/>
    <!-- Static Resource Config -->
    <mvc:resources location="/WEB-INF/static/" mapping="/static/**" />
    <!-- ViewResolver Config -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <bean id="testController" class="com.example.controller.TestController">
    </bean>
 
</beans>
 
cs


web.xml (아참 applicationContext , listener 부분까지 지금 소스가 나와있는데. 
아직 안쓰니까 주석처리해야 된다 3단계 디비처리에서 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
34
35
36
37
38
39
40
41
42
43
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
    
    
    <!-- 03. Dispatcher Servlet Config -->
     <servlet>
          <servlet-name>dispatcherServlet</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
               <param-name>contextConfigLocation</param-name>
               <param-value>/META-INF/spring/dispatcherServlet.xml</param-value>
          </init-param>
          
     </servlet>
     <servlet-mapping>
          <servlet-name>dispatcherServlet</servlet-name>
          <url-pattern>/</url-pattern>
     </servlet-mapping>
     
   
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
              /META-INF/spring/applicationContext.xml
          </param-value>
    </context-param>
 
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    
</web-app>
 
cs


그리고 이제 localhost:8080 로 접속하여서 확인해본다. 

아참 여기서 쓰는 jsp 파일은 web-app 폴더내의 index.jsp 이다. 

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello appengine + maven<br>
<a href="/spring">스프링으로 이동!</a>
</body>
</html>
cs




3부 database 연동

pom.xml dependencies 추가부분

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
 
<!-- 여기가 세번째 db추가였던가.  -->
        <!-- Spring & DB 추가 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring Data JPA -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring.data.jpa}</version>
        </dependency>
 
 
        <!-- db관련 라이브러리 -->
        <!-- Datanucleus -->
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-core</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-api-jpa</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-enhancer</artifactId>
            <version>3.1.1</version>
        </dependency>
        
        <!-- 이것이 있어야 앱엔진에서 datanucleus 를 쓸 수 있다. 2버젼에서 더 이상 개발안하는듯? -->
        <!-- 2버젼이 datanucleus 3버젼대를 지원한다. -->
        <dependency>
            <groupId>com.google.appengine.orm</groupId>
            <artifactId>datanucleus-appengine</artifactId>
            <version>2.1.2</version>
        </dependency>
cs


pom.xml build 안의 plugins 추가부분

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- Spring & db 추가하면서 넣은 플러그인 enhancer를 위해 쓴다 -->
            <plugin>
                <groupId>org.datanucleus</groupId>
                <artifactId>datanucleus-maven-plugin</artifactId>
                <version>3.3.2</version>
                <configuration>
                    <api>JPA</api>
                    <persistenceUnitName>MyUnit</persistenceUnitName>
                    <log4jConfiguration>${basedir}/src/main/resources/log4j.properties</log4jConfiguration>
                    <verbose>true</verbose>
                </configuration>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
cs


src/main/resources 폴더안의 META-INF 폴더안의 persistence.xml 파일 내용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/persistence"
    xsi:schemalocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 
    <persistence-unit name="MyUnit">
        <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
        <properties>
            <class>com.example.domain.TestClass</class>
            <property name="datanucleus.ConnectionURL" value="appengine" />
            <property name="datanucleus.appengine.datastoreEnableXGTransactions" value="true" />
            <property name="datanucleus.appengine.ignorableMetaDataBehavior" value="NONE" />
        </properties>
    </persistence-unit>
 
</persistence>
cs


applicationContext.xml 작성해야함 ( webapp/META-INF/spring ) 에 넣었다. 

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
 
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
 
 
    <jpa:repositories base-package="com.example.repository" />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <constructor-arg ref="entityManagerFactory" />
    </bean>
 
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="MyUnit" />
        <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"></property>
        <property name="packagesToScan" value="com.example.domain" />
         <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
        </property> 
    </bean>
 
</beans>
 
cs


그 후 컨트롤러 완성...

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
package com.example.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.example.domain.TestClass;
import com.example.repository.TestRespository;
 
@Controller
public class TestController {
 
    @Autowired
    TestRespository repository;
    
    @RequestMapping("/spring")
    String index(){
        return "index";
    }
 
    
    @RequestMapping("list")
    String list(Model model){
        List<TestClass> userList = repository.findAll();
        System.out.println(userList);
        model.addAttribute("userlist", userList);
        return "list";
    }
    
    @RequestMapping("add")
    String add(TestClass member){
        repository.save(member);
        return "redirect:/list";
    }
    
    String update(){
        return "redirect:/list";
    }
 
}
 
 
cs


jpa 인터페이스 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
package com.example.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
import com.example.domain.TestClass;
 
import java.lang.Long;
import java.util.List;
 
 
public interface TestRespository extends JpaRepository<TestClass, Long> {
    List<TestClass> findByname(String name);
}
 
cs


web-inf의 appengine-web.xml 도 이렇게 나온다. 거의 내버려두면 될듯.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <!-- 이부분을 프로젝트 아이디로 설정해주면 된다.  -->
    <application>soy-bridge-792</application>
    <!-- 여기가 버젼이 다른 부분이다. 이곳을 다른 버젼으로 만들어주면 다른 버젼으로 올라간다.  -->
    <version>1</version>
    <threadsafe>true</threadsafe>
    
    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
    </system-properties>
</appengine-web-app>
 
cs


jsp 파일들을 굳이 같이 올리자면 다음과 같다. web-inf/jsp 폴더 안에 있다.

이것은 index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>InsertTitleMessage</title>
</head>
<body>
hello sprig in appengine with maven
 
    <h3>새로운 유저와 메시지</h3>
    <form action="/add">
        name : <input type="text" name="name"><br> message : <input
            type="text" name="message"><br> <input type="submit">
    </form>
    
</body> 
</html>
cs




음 마지막 list.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>InsertTitleMessage</title>
</head>
<body>
    <h3>유저 리스트</h3>
    <c:forEach var="user" items="${userlist}">
    username : ${user.name } ,  user_message : ${user.message } <br>
    </c:forEach>
 
    <h3>새로운 유저와 메시지</h3>
    <form action="/add">
        name : <input type="text" name="name"><br> message : <input
            type="text" name="message"><br> <input type="submit">
    </form>
 
</body>
</html>
cs