IDEA搭建Spring + Spring MVC + hibernate

工具:IDEA(jdk 1.8) spring和hibernate版本均爲4.0以上
推薦使用maven構建項目,相比自己手動導入jar包要方便很多。

1.新建一個maven web項目。

IDEA搭建Spring + Spring MVC + hibernate

先建一個maven項目,建項目這裏不多說,
正確的文件結構:
-src
---main
------java(class文件)
------resources(配置文件)
------webapp(web文件)
---test(測試文件)
------java
------resources

2、編寫pom.xml文件,導入jar包

導入jar包也是框架整合中比較麻煩的點,常常會導入太多不相關的包,但由於不熟悉又不敢刪掉,於是jar包越導越多,到最後框架是搭起來,但jar包卻導了十幾二十個。
注意點:這裏建議的做法是當你不熟悉框架需要導入什麼jar包時,可以先導入核心包,然後當運行項目時提示NotFoundClass時,再根據錯誤提示添加相關的依賴,這樣就不會導入多餘的jar包。
可以到該網站上去搜索你需要的依賴:https://mvnrepository.com/

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zznode</groupId>
    <artifactId>admin</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>admin Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <!-- spring版本號 -->
        <spring.version>4.3.10.RELEASE</spring.version>
    </properties>

    <!--   依賴從這開始
     <dependencies>是所有依賴包的父級標籤
     其中每添加一個依賴包,就加一個<dependency>標籤
     這裏已經默認添加了一個測試包,我們需要把所有用到的依賴全部進來
     (用到每個包的依賴信息需要自己找,下面是這個demo需要的依賴包)
     -->
    <!--項目依賴 -->
    <dependencies>
        <!--日誌包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.8.7</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!--mysql驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <!-- 添加Hibernate依賴 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.8.Final</version>
        </dependency>

        <!--  &lt;!&ndash; spring-date-jpa&ndash;&gt;
          <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.0.6.RELEASE</version>
          </dependency>
      -->
        <!-- https://mvnrepository.com/artifact/javassist/javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <!-- Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--Spring MVC + Spring web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--其他需要的包-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--  &lt;!&ndash; https://mvnrepository.com/artifact/com.google.code.gson/gson &ndash;&gt;
          <dependency>
              <groupId>com.google.code.gson</groupId>
              <artifactId>gson</artifactId>
              <version>2.8.0</version>
          </dependency>-->
        <!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!--c3p0 start -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>admin</finalName>

    </build>
</project>
其中,註釋塊 <spring> <springmvc> <hibernate>中的依賴導入了框架核心jar包,我們可以提前導入,其他的我們可以根據提示或者需求進行改動。
比如,我的項目中使用的是mysql數據庫和c3p0數據源,所以引入MySQL和c3p0的依賴,如果你使用的是其他數據庫和數據源就需要做相應的修改。
pom文件中爲註釋的部分則是在項目運行時提示的jar包缺失引入的依賴,有的是spring框架依賴的包,有的則是servlet或者jsp依賴的,如果第一次搭建時不熟悉可以先不導入,等報錯時再引入依賴,這樣也可以加深理解。

3、配置文件

這是框架整合最重要的部分。配置文件除了web.xml之外都放在main/resources文件夾中,當然你也可以放在其他自己新建的文件夾下,不過配置文件地址要做相應的修改,這個等會詳細說。
配置文件的配置,很多框架整合的教程都不太一樣的,這裏給出我自己的配置方法和做法。
配置文件主要分爲四個:web.xm , beans.xml , spring-mvc.xml , datasource.xml 。
配置步驟分爲兩步,spring-mvc和spring的整合,hibernate和spring的整合,最後再運行項目。(這也是效率比較高的做法,分開整合,這樣即使運行項目有報錯也比較好找,而且分部整合不容易亂)
接下來就開始具體配置。

4、spring-mvc和spring整合

spring-mvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--啓用spring的一些annotation -->
    <context:annotation-config/>

    <!-- 自動掃描com.test.controller包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="com.zznode.admin.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <!--排除@service註解的類-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>

    <!-- 配置註解驅動 可以將request參數與綁定到controller參數上 -->
    <mvc:annotation-driven/>

    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前後綴(如果最後一個還是表示文件夾,則最後的斜槓不要漏了) 使用JSP-->
    <!-- 默認的視圖解析器 在上邊的解析錯誤時使用 (默認使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/><!--設置JSP文件的目錄位置-->
        <property name="suffix" value=".html"/>
    </bean>

    <!-- springmvc文件上傳需要配置的節點-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20971500"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="resolveLazily" value="true"/>
    </bean>

    <!-- 使用jackjson,默認將返回對象轉換爲 JSON,如果前面沒有在pom文件中添加jackson包的不需要這個配置  -->
    <bean id="stringConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>
</beans>
這是spring-mvc基本的配置,主要是對請求和靜態資源映射的配置。
注意點
1.需要特別注意的是掃描包時要排除service層的類,不然在整合hibernate後,項目運行時會報錯。
具體原因看一下這個網址:http://blog.csdn.net/xiaobao5214/article/details/52042041
2.然後就是如果你的包名和結構不一樣的,那麼掃描的包地址也要記得更換。

web.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>
    <display-name>admin</display-name>

    <!-- 統一編碼 解決中文亂碼問題-->
    <filter>
        <filter-name>charsetEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>charsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring MVC 配置-->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 此處指向的的是SpringMVC的配置文件 如果配置文件地址和名稱不一樣需要更改-->
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!--配置容器在啓動的時候就加載這個servlet並實例化-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring MVC config end-->

</web-app>
將spring-mvc配置文件加到web.xml中,當服務器啓動項目時,纔會加載springmvc。配置完成後寫個例子測試一下。
先在bean包中創建一個User類(測試ackjson)
package com.zznode.admin.bean;

public class User {

    private int id;
    private int age;
    private String name;

    public User(){ }

    public User(int id, int age, String name){
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
先在controller包中創建TestController.class:
package com.zznode.admin.controller;

import com.zznode.admin.bean.People;
import com.zznode.admin.bean.User;

import com.zznode.admin.service.PeopleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("test")
public class TestController {

    @Resource(name="peopleService")
    private PeopleService peopleService;

    @GetMapping("/hello")
    @ResponseBody//表示直接輸出返回內容,不進行jsp或html跳轉,本例是爲了寫接口,這裏直接返回json
    public User test(){

        User user = new User(1,2,"瑞文");
        return user;
    }

}
現在的目錄結構如下:

IDEA搭建Spring + Spring MVC + hibernate

啓動項目,在瀏覽器中輸入地址:http://localhost:8080/(項目名)/test 。成功可以看到頁面。

IDEA搭建Spring + Spring MVC + hibernate
這裏大家有疑問,我返回的是一個對象爲什麼頁面顯示的是json數據。可以看我在web.xml配置了jackjson,使用jackjson,默認將返回對象轉換爲 JSON。有興趣的話大家可以去了解下。spring mvc現在配置完了,現在去配置hibernate.

5、spring和hibernate整合

datasource.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:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!--配置數據源 這裏是使用的是c3p0連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />  <!--數據庫連接驅動-->
        <property name="jdbcUrl" value="${jdbc.url}" />     <!--數據庫地址-->
        <property name="user" value="${jdbc.username}" />   <!--用戶名-->
        <property name="password" value="${jdbc.password}" />   <!--密碼-->
        <property name="maxPoolSize" value="40" />      <!--最大連接數-->
        <property name="minPoolSize" value="1" />       <!--最小連接數-->
        <property name="initialPoolSize" value="10" />      <!--初始化連接池內的數據庫連接-->
        <property name="maxIdleTime" value="20" />  <!--最大空閒時間-->
    </bean>

    <!--配置session工廠-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.zznode" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根據實體自動生成數據庫表-->
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>   <!--指定數據庫方言-->
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>     <!--在控制檯顯示執行的數據庫操作語句-->
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!--在控制檯顯示執行的數據哭操作語句(格式)-->
            </props>
        </property>
    </bean>

    <!-- 事務配置 聲明式事務-->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 使用annotation定義事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

applictionContext.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 註解 -->
    <context:annotation-config />
    <!--掃描-->
    <context:component-scan base-package="com.zznode">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 導入多個Properties配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!--要是有多個配置文件,只需在這裏繼續添加即可 -->
                <value>classpath:datasource.properties</value>
            </list>
        </property>
    </bean>
    <!-- 加載數據源組件 -->
    <import resource="classpath:datasource.xml" />
</beans>
注意點:在xml導入properties文件是比較常見,將一些相關的配置數據寫到properyties文件中也是常用的方法,利於修改。
常見的另一種導入propertise的方法:在<context:property-placeholder location="classpath:/datasource.properties" />。這種方法spring默認值只導入一個properties,
當有多個properties文件需要導入時,則需要使用另一種方法:
<!-- 導入多個Properties配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!--要是有多個配置文件,只需在這裏繼續添加即可 -->
                <value>classpath:datasource.properties</value>                
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>
個人比較推薦這種,隨着項目擴展,需要導入的配置增多,肯定不止一個properties文件,這種方法更通用。
注意點:datasource.properties文件中的數據庫地址,用戶和密碼根據自己的情況做相應的修改。

修改之前的web.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>
<display-name>admin</display-name>

  <!-- 統一編碼 解決中文亂碼問題-->
  <filter>
    <filter-name>charsetEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>charsetEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring MVC 配置-->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- 此處指向的的是SpringMVC的配置文件 如果配置文件地址和名稱不一樣需要更改-->
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!--配置容器在啓動的時候就加載這個servlet並實例化-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- spring MVC config end-->

  <!-- 加載spring配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applictionContext.xml</param-value>
  </context-param>
  <!-- listener -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>
這就是spring整合hibernate所需要配置的四個文件。文件的加載順序和包含關係:web.xml→bans.xml→datasource.xml→datasource.properties
注意點:如果你的配置文件名稱和存放位置不同,那麼你也需要相應的修改。
注意點:一定要記得配置事務,否則操作數據庫時項目可能不會報錯,但數據庫中的數據將不會更新(刪除或者修改)。具體可以自行百度事務相關的知識。
配置完成後寫個例子測試一下。
在bean包中創建People.class:
package com.zznode.admin.bean;

import javax.persistence.*;

@Entity
@Table(name="people")
public class People {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="sex")
    private String sex;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

}

然後在dao包中創建PeopleDao.class:

package com.zznode.admin.dao;

import com.zznode.admin.bean.People;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository("peopleDao")
public class PeopleDao {

    @Resource(name="sessionFactory")
    private SessionFactory sessionFactory;

    /**
     * 保存對象
     * @param p
     * @return
     */
    public void save(People p){
        sessionFactory.getCurrentSession().save(p);
    }
}

在service包中創建PeopleServic.class:

package com.zznode.admin.service;

import com.zznode.admin.bean.People;
import com.zznode.admin.dao.PeopleDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("peopleService")
public class PeopleService {

    @Resource(name="peopleDao")
    private PeopleDao peopleDao;

    @Transactional
    public void save(People p){
        peopleDao.save(p);
    }

    public People newPeople(){
        People p=new People();
        p.setName("小白");
        p.setSex("男");
        return p;
    }

}
注意點:在save方法上加@Transactional註解來開啓事務。
在DemoController.class中調用save方法保存數據:
package com.zznode.admin.controller;

import com.zznode.admin.bean.People;
import com.zznode.admin.bean.User;

import com.zznode.admin.service.PeopleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("test")
public class TestController {

    @Resource(name="peopleService")
    private PeopleService peopleService;

    @GetMapping("/hello")
    @ResponseBody//表示直接輸出返回內容,不進行jsp或html跳轉,本例是爲了寫接口,這裏直接返回json
    public User test(){

        User user = new User(1,2,"瑞文");
        return user;
    }

    @GetMapping("/save")
    @ResponseBody
    public People savePeople(){
        People people = new People();
        people.setSex("男");
        people.setName("泰達米爾");
        peopleService.save(people);
        return people;
    }

}

啓動服務器,訪問項目。刷新數據庫,如果數據保存到數據庫中了,說明框架搭建完成。

訪問http://localhost:8080/(項目名)/test 。成功可以看到頁面。

IDEA搭建Spring + Spring MVC + hibernate

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章