1. 程式人生 > >idea 搭建maven+spring mvc+jpa框架

idea 搭建maven+spring mvc+jpa框架

在此之前,對於搭建這樣一個框架很是苦惱,總是出錯 ,今天,作為一個初學者,將自己實驗多次的成功的步驟復原,希望能幫到需要的人

先說一下步驟流程(我認為比較快的步驟)

1、建立maven工程,並配置tomcat(看下一篇部落格)

2、建立java資料夾

3、配置pom.xml

4、新建並配置applicationContext.xml和  dispatcher-servlet.xml

5、配置web.xml

6、配置jpa

一、建立java資料夾

1、在src>>main資料夾下新建一個Directory,檔名為java;然後右鍵點選Mark Directory as --Generated Source Root

2、在檔案下建立4個包 package(domain,dao,service,controller)之前先建一個java class,類名隨便起,用不到;

二、配置pom.xml

pom.xml的作用就是載入jar包的作用,把需要的jar包引用一下 (如果沒有下載下來就在pom.xml頁面右鍵點選maven-reimport自動載入jar 包)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>xyz</groupId>
  <artifactId>demo124</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>demo200 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--spring jar包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.7.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.3.RELEASE</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-commons-annotations</artifactId>
      <version>3.2.0.Final</version>
    </dependency>
    <!--JPA jar 包-->

    <!--oracle-->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.3</version>
    </dependency>

    <!--hibernate-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.11.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-spatial</artifactId>
      <version>4.3</version>

    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.11.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.1-api</artifactId>
      <version>1.0.0.Final</version>
    </dependency>

    <!--日誌jar-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.5</version>
      <scope>provided</scope>
    </dependency>

    <!--json-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.5.1</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-lgpl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-lgpl</artifactId>
      <version>1.9.13</version>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.4</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>jcifs</groupId>
      <artifactId>jcifs</artifactId>
      <version>1.3.17</version>
    </dependency>

    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.0</version>
    </dependency>

    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-websocket</artifactId>
      <version>8.0.23</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
    <dependency>
      <groupId>jaxen</groupId>
      <artifactId>jaxen</artifactId>
      <version>1.1.6</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>demo124</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
      </plugin>
    </plugins>
  </build>
</project>


三、新建並配置spring MVC 的配置檔案

在第二個步驟匯入jar包,在src>>main>>resource下新建兩個xml檔案(applicationContext.xml和  dispatcher-servlet.xml)

檔名稱可以按照我的寫,方便後面關係的對應

接下來配置這兩個檔案

先看一下我的目錄結構:

先來配置applicationContext.xml

<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">


    <!--初始entity實體管理器-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="permissionPersistenceUnit"/>
    </bean>
    <!--初始transaction事務管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--初始化spring JPA-->
    <!--注意下面的package 路徑,對應目錄下的dao層
-
->  <jpa:repositories base-package="com.geoway.test.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" repository-impl-postfix="Impl"> <!--factory-class="com.geoway.monitor.dao.BaseDaoRepositoryFactoryBean">--> </jpa:repositories> <!-- 建立檢視內攔截器來解決JPA中訪問延遲載入屬性時產生的無會話異常 --> <!-- LazyInitializationException: could not initialize proxy no session --> <!-- 此攔截器會注入到servlet配置中的DefaultAnnotationHandlerMapping中 --> <bean name="openEntityManagerInViewInterceptor" class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor"> <property name="entityManagerFactory"> <ref bean="entityManagerFactory" /> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="openEntityManagerInViewInterceptor" /> </list> </property> </bean> </beans>


然後再來配置dispatcher-servlet.xml檔案

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!--<!– 啟動包掃描功能,以便註冊帶有@Controller、@service、@repository、@Component等註解的類成為spring的bean –>-->
    <context:component-scan base-package="com.geoway.test"/>
    <!--<mvc:resources mapping="/resources/**" location="/WEB-INF/pages/"></mvc:resources>-->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="favorPathExtension" value="false" />
        <property name="favorParameter" value="false" />
        <property name="ignoreAcceptHeader" value="false" />
        <property name="mediaTypes" >
            <value>
                html=text/html
                json=application/json
            </value>
        </property>
    </bean>

   
</beans>

四、配置web.xml,瀏覽器執行的時候會首先讀取web.xml檔案(主要是在檔案裡配置找到上面兩個.xml檔案的路徑)
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          version="3.0">

  <!-- 載入spring配置檔案  指定Spring Bean的配置檔案所在目錄 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 載入mvc servlet配置檔案-->
  <servlet>
    <!--注意下面的servlet-name的名稱可以自定義,但是下面的servlet-mapping標籤下面的servlet-name一定要和自己定義的名稱一樣-->
    <servlet-name>mvc-dispatcher</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <!--下面的servlet-name的名稱mvc-dispatcher來找到上面的servlet-name名稱。然後找到 dispatcher-servlet.xml檔案-->
    <servlet-name>mvc-dispatcher </servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

五、終於配置的差不多了,但是執行會報錯(建立實體管理entityManager出錯)那是因為資料庫的操作沒有配置好,所以耐下心來,好事情總是值得等待的~~~吐舌頭

那我們可就來做最後一步的操作:配置JPA,生成persistence.xml的方法有兩種,我先演示一下利用jpa(非本地的)生成的吧

1、點選project structure 在右上角,見圖所示:

2、如下圖,如果沒有模組下面沒有jpa就要自己新建一個,點選紅色數字標註的加號,選擇JPA,然後點選目錄下的JPA,然後點選3處的加號,選擇persistence.xml,路徑一般放在模組名稱\src\main\resources\META-INF\persistence.xml,上面的兩個配置檔案也要放在resource裡面

3、生成的persistence.xml你會發現裡面是空的,裡面是要裝一下資料庫的配置資訊,配置之前需要先連線一下資料庫,我的是Oracle資料庫

寫到這裡發現已經寫得好多了,對不初學者來說腦子一定暈得很,想把它拆開寫吧,但是又覺得拆開了沒有邏輯感了,就這樣按照這個邏輯下去吧,咱先來連線一下資料庫

3.1、剛才咱不是生成了persistence.xml了嘛,咱現在就來點他,我的工程就是demo124,選擇generate persistence mapping 的By database schema

3.2  接下來就彈出一個介面(資料庫我的不是本地的,連的是公司的伺服器上的)


上面的設定知道第五步出現successful 才說明你庫連上了

然後回到步驟1的介面,我們選一張表生成一個實體,看看


ok 之後會在domian層下面生成一張表的實體,

接下來    終於  終於     到最後一步了:配置persistence.xml(加油,加油)(注意,有兩種配置方式,下面我註釋掉的是系統自動生成的,但是我執行就報錯,說生成實體管理失敗,我找了好多辦法,試了下下面的用下面的寫法就成功了,其實我覺得主要還是有有使用者名稱和密碼啥的)

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit  name="permissionPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <!--下面是我生成的一張使用者表-->
 <class>com.XXX.test.domain.TbYxuser</class>
    <!--<properties>--> 

        <!--<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@//db11gr1.XXX.net:1521/db11g"/>-->
        <!--<property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>-->
        <!--<property name="hibernate.connection.url" value="jdbc:oracle:thin:@//db11gr1.XXX.net:1521/db11g"/>-->
        <!--<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>-->
        <!--<property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:@//db11gr1.XXX.net:1521/db11g"/>-->
        <!--<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.OracleDriver"/>-->
        <!--<property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@//db11gr1.XXX.net:1521/db11g"/>-->
        <!--<property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>-->
    <!--</properties>-->

    <properties>
        <property name="hibernate.connection.url" value="jdbc:oracle:thin:@//db11gr1.XXX.net:1521/db11g"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>

        <property name="hibernate.connection.username" value="XXX"/>
        <property name="hibernate.connection.password" value="XXX"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.max_fetch_depth" value="5"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
</persistence-unit>

</persistence>

。。。。。。。。。。。到這一步終於寫完了。勞心勞力,

如果執行後還老是出現這樣的問題,那就要需要注意我說的在配置的過程中強調的了

SEVERE: Exception sending contextinitialized event to listener instance of classorg.springframework.web.context.ContextLoaderListener

org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'entityManagerFactory' defined in class pathresource [applicationContext.xml]: Invocation of init method failed; nestedexception is javax.persistence.PersistenceException: Unable to build entitymanager factory

看一下執行的結果:

  

           開心吧~~~~啦啦啦

我現在自己不看網上的案例自己就能很快的搭建起來這樣的框架,突然有點佩服自己了,想想自己一開始什麼都不會,老是吐槽為啥這麼多的檔案,也不知他們之間的聯絡是啥,所以老是缺這少那的,走一步卡一步,還好自己沒放棄,一步步的來,關鍵在於遇到問題了要去解決而不是逃避,要不然,自己永遠什麼都學不會。