框架搭建-Spring+SpringMVC+Hibernate
一、 專案環境
1.1、環境
Intellij Idea+Spring4.0+SpringMVC4.0+Hibernate4.0+Mysql5.1
1.2、包結構
1.3、包功能
- 1)com.spring.zbt.controller:Phone應用的Controller層,主要用來處理瀏覽器的請求;
- 2)com.spring.zbt.service:Phone應用的Service層,主要有一個PhoneService介面和實現了該介面的類PhoneServiceImpl。Service層的目的主要是解耦DAO層和Controller層;
3)com.spring.zbt.dao:Phone應用的DAO層,包含PhoneDaO介面和實現了該介面的類PhoneDaoImpl。DAO層使用Hibernate的API和資料庫進行互動;
4)com.spring.zbt.model:包含一個簡單的POJO類,主要的屬性有id、name、review
二、依賴
2.1使用Maven工具管理我們的專案依賴的Jar包;主要引入的包有
//Spring相關
spring-context、spring-webmvc、spring-tx、spring-orm
//Hibernate相關
hibernate-core、hibernate-entitymanager
//資料來源和資料庫相關
com.mchange.c3p0、mysql-connector-java
//servlet相關
javax.servlet-api、javax. servlet.jsp-api、javax.servlet.jstl
taglibs-standard-jstlel、taglibs-standard-impl
//日誌相關
slf4j-api
//javax注入相關
javax.inject
2.2、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.spring.demo</groupId>
<artifactId>SpringMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVC Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
<c3p0.version>0.9.5.2</c3p0.version>
<mysql.version>5.1.44</mysql.version>
<taglibs.version>1.2.5</taglibs.version>
</properties>
<dependencies>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!--Hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--C3P0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--Aspectj
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>-->
<!--Logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<[email protected]>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>${taglibs.version}</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-jstlel</artifactId>
<version>${taglibs.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
三、建立資料庫和表
3.1建立spring資料庫
create database spring;
use spring
3.2建立phone表
create table phone(id int(11) auto_increment not null primariy key,
name varchar(50) not null,
review varchar(20) default null);
desc phone;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| review | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+----------------+
四、實體類
首先建立一個Hibernate POJO用於儲存Phone的資訊,同時我們需要將這個類對映到資料庫中相應的表
package com.spring.zbt.model;
import javax.persistence.*;
@Entity
@Table(name="phone")
public class Phone {
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="name")
private String name;
@Column(name="review")
private String review;
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 getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}
@Entity:主要是告訴Hibernate這個類代表一個可持久化的物件
@Table:告訴Hibernate這個類與資料庫中哪張表進行對映
@GenerateValue:表明這個被註解的屬性的值是由dataSource決定的,而不是由程式設計寫入的
@Column(name=”name”):用於對映Phone這個類中的name屬性到phone表中的name這一column
@Column(name=”review”):用於對映Phone這個類中的review屬性到phone表中的review這一column
五、 DAO層
Phone.Dao
import com.spring.zbt.model.Phone;
import java.util.List;
public interface PhoneDao {
public void addPhone(Phone phone);
public void updatePhone(Phone phone);
public List<Phone> listPhones();
public Phone getPhoneById(int id);
public void removePhone(int id);
}
2、PhoneDaoImpl.java
package com.spring.zbt.dao;
import com.spring.zbt.model.Phone;
import com.spring.zbt.service.PhoneService;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
public class PhoneDaoImpl implements PhoneDao {
//private static final Logger logger = LoggerFactory.getLogger(PhoneDaoImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public void addPhone(Phone phone) {
this.sessionFactory.getCurrentSession().save(phone);
}
public void updatePhone(Phone phone) {
this.sessionFactory.getCurrentSession().update(phone);
}
public List<Phone> listPhones() {
String hql ="select phone from Phone phone";
return this.sessionFactory.getCurrentSession().createQuery(hql).list();
}
public Phone getPhoneById(int id) {
String hql = "select phone from Phone phone where id= :id";
return (Phone) this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("id",id).uniqueResult();
}
public void removePhone(int id) {
Phone phone = this.sessionFactory.getCurrentSession.load(Person.class,new Integer(id));
if(phone != null){
this.sessionFactory.getCurrentSession().delete(phone);
}
}
}
@Repository:
六、Service層
PhoneSerivce.java
package com.spring.zbt.service;
import com.spring.zbt.model.Phone;
import java.util.List;
public interface PhoneService {
public void addPhone(Phone phone);
public void updatePhone(Phone phone);
public List<Phone> listPhones();
public Phone getPhoneById(int id);
public void removePhone(int id);
}
PhoneServiceImpl.java
package com.spring.zbt.service;
import com.spring.zbt.dao.PhoneDao;
import com.spring.zbt.dao.PhoneDaoImpl;
import com.spring.zbt.model.Phone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by luckyboy on 2018/7/12.
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class PhoneServiceImpl implements PhoneService {
@Autowired
private PhoneDao phoneDao;
public void setPhoneDao(PhoneDaoImpl phoneDao){
this.phoneDao = phoneDao;
}
@Transactional
public void addPhone(Phone phone) {
this.phoneDao.addPhone(phone);
}
@Transactional
public void updatePhone(Phone phone) {
this.phoneDao.updatePhone(phone);
}
@Transactional
public List<Phone> listPhones() {
return this.phoneDao.listPhones();
}
@Transactional
public Phone getPhoneById(int id) {
return this.phoneDao.getPhoneById(id);
}
@Transactional
public void removePhone(int id) {
this.phoneDao.removePhone(id);
}
}
@Service
- 表明這個類是一個”Service”類
- 其實我們也可以使用@Component這個註解實現
@Transactional
- 使Spring具有事務的行為
- @Transactional註解可以被用在類、方法、介面上
- 其中readOnly=true屬性表明這個事務僅僅是可讀的,不能對資料進行任何修改
- 如果要使用這個註解,我們需要在上下文中配置包掃描和事務註解驅動
<context:component-scan base-package="com.spring.zbt.*"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
@Autowired
- 使這個域通過spring依賴注入的方式進行注入
- 使這個域在構造這個域之後注入屬性,但是在config方法出發前注入
- 通過配置檔案的元資料的資料型別的方式制動裝配Bean例項
七、 Presentation 層
package com.spring.zbt.controller;
import com.spring.zbt.model.Phone;
import com.spring.zbt.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PhoneController {
private PhoneService phoneService;
@Autowired(required = true)
@Qualifier(value = "phoneService")
public void setPhoneService(PhoneService phoneService){
this.phoneService = phoneService;
}
@RequestMapping(value="/phones",method= RequestMethod.GET)
public String listPhones(Model model){
model.addAttribute("phone",new Phone());
model.addAttribute("listPhones",this.phoneService.listPhones());
return "phone";
}
@RequestMapping(value="/phone/add",method=RequestMethod.POST)
public String addPhones(@ModelAttribute("phone") Phone phone){
if(phone.getId() == 0){
this.phoneService.addPhone(phone);
}else{
this.phoneService.updatePhone(phone);
}
return "redirect:/phones";
}
@RequestMapping(value="/remove/{id}")
public String removePhone(@PathVariable("id") int id){
this.phoneService.removePhone(id);
return "redirect:/phones";
}
@RequestMapping("/edit/{id}")
public String editPhone(@PathVariable("id") int id,Model model){
model.addAttribute("phone",this.phoneService.getPhoneById(id));
model.addAttribute("listPhones",this.phoneService.listPhones());
return "phone";
}
}
@Controller
- 此註解表明PhoneController類充當”Controller”的角色
- 為了能夠自動檢測到這個註解的controller,應該在配置檔案servlet-context.xml中新增
<context:component-scan base-package="com.spring.zbt.*"/>
@Autowired
- 通過將一個構造方法或者是setters方法由Spring的依賴注入裝置自動注入
- 在bean例項被構造以後被注入,
- 通過匹配配置檔案的元資料來注入bean
@Qualifier
- 和@Atuowired註解一起使用,防止出現衝突
- 使用name這個屬性去除歧義
@RequestMapping
- DispatcherServlet 通過這個註解以分配request到正確的controller(是一個類)和handler(類中的方法)上
- 在handler方法上使用@RequestMapping使得handler有靈活的返回值
九、web配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
十、servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:annotation-config/>
<!--配置資料來源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>
<property name="user" value="root"/>
<property name="password" value="zbt123456"/>
</bean>
<!--定義Hibernate4 SessionFactory Bean-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.spring.zbt.model.Phone</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<bean id="phoneDao" class="com.spring.zbt.dao.PhoneDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="phoneService" class="com.spring.zbt.service.PhoneServiceImpl">
<property name="phoneDao" ref="phoneDao"/>
</bean>
<context:component-scan base-package="com.spring.zbt.*"/>
<!--因為使用了註解設定事務的方式,因此我們需要設定註解驅動方案-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref = "sessionFactory"/>
</bean>
</beans>
翻譯文章
相關推薦
框架搭建-Spring+SpringMVC+Hibernate
一、 專案環境 1.1、環境 Intellij Idea+Spring4.0+SpringMVC4.0+Hibernate4.0+Mysql5.1 1.2、包結構 1.3、包功能 1)com.spring.zbt.controller
基於spring boot搭建spring+springMVC+hibernate+mysql
版本: spring boot:2.1.0.RELEASE mysql:8.0.12 1、新增起步依賴 pom.xml檔案 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.a
SSM框架搭建(Spring+SpringMVC+MyBatis)
SSM框架搭建 目錄 一丶概述介紹 1.SSM介紹 二丶需求分析 搭建SSM框架 三丶步驟分析以及操作 一丶概述介紹 SSM(Spring+Sp
一步步學java框架之Spring-SpringMVC-Hibernate在idea的使用(三)
本專題主要學習Spring-SpringMVC-Hibernate的使用,作者我也是最近開始學習java框架,所以有什麼錯的請提出。 這節我們來寫spring-dispatcher-servlet檔案和寫Controller(控制器) 我們先把原來要
Spring+Springmvc+Hibernate框架搭建,簡單例項
最近學習spring框架,學習中總是磕磕絆絆的,出現這樣或者那樣的問題,於是就像寫一篇筆記,將spring,springmvc,hibernate框架整合的過程,以及簡單的實現記錄下來,一來加深印象,二來一遍以後忘記好找資料(...)當然,初學者也可以借鑑一下。廢話不多說,
框架搭建(SpringMVC+Spring+hibernate )
spring版本:3.0.5 hibernate版本:3.3 簡介:Spring MVC Spring MVC(Model View Controller)是 Spring 中一個重要的組成部分。 Spring MVC 框架處理請求的流程: Spring MVC 核心
(實用篇)一步步搭建Spring+SpringMVC+MyBatis(SSM)框架
一、前言 本篇內容是培訓作業的第一個任務,旨在搭建一個SSM框架,做一個HTML頁面,能查詢,能插入資料(新建使用者)、登陸。實現的功能最為基礎,但是要求所有程式碼均為手寫,不能使用Mybatis 自動生成mapping和dao。由於此框架是後面一系列任務的基礎,所以,還是
基於Maven工具搭建Spring+SpringMVC++MyBatis(ssm)框架步驟
目錄 1.使用Ecplise建立Maven工程: 2.構建SSM框架 3.日誌資訊:log4j 4.應用例項:使用者登入 5 資料庫MySQL 1.使用Ecplise建立Maven工程: 1.1 File -> New -> Other,在New視
springMVC系列之(四) spring+springMVC+hibernate 三大框架整合
首先我們要知道Hibernate五大物件:,本例項通過深入的使用這五大物件和spring+springMVC相互結合,體會到框架的好處,提高我們的開發效率 Hibernate有五大核心介面,分別是:Session Transaction
使用maven搭建SSH專案(spring+springmvc+Hibernate)
本文介紹使用eclipse+maven搭建Spring+SpringMvc+Hibernate專案,以登陸為例: 1、建立maven專案 2、把maven專案變為動態網站 3、搭建spring+springmvc+Hibernate專案 1 建立maven專案
基於maven搭建spring+springMVC+mybatis(SSM)框架專案
一.簡介 這篇文章是記錄我自己手動搭建基於maven的SSM(spring+springMVC+mybatis)框架專案的整個過程,目的是為了加深印象和方便以後查閱以及整理思路。 二.開發環境準備 (1)系統:Windows10(專業版) (2)eclispe版本:Eclipse J
java知識Servlet與五大框架(Spring,hibernate,mybatis,struts2,SpringMVC)總結
----------------------JDBC部分---------------------------- JDBC工作原理主要分3個步驟:1、載入資料庫驅動。2、獲取資料庫連線。3、傳送sql語句訪問資料庫 1、載入資料驅動:使用Class.forName方法,
框架篇:Spring+SpringMVC+hibernate整合開發
前言: 最近沒什麼事做,搭個框架寫成部落格記錄下來,拉通一下之前所學知識. 話不多說,我們直接步入正題。 準備工作: 1/安裝並配置java執行環境 2/資料庫的安裝配置(Mysql) 3/安裝並配置伺服器(Tomcat)
利用Maven搭建Spring+SpringMVC+Mybatis框架專案(二)
上次寫到將Spring和Mybatis整合到了一起,這次便將SpringMVC整合進去,SpringMVC只負責controller和頁面之間的跳轉,也就是隻負責和使用者互動 3.2 整合SpringMVC框架 3.2.1 建立spring-mvc.xml
基於spring+springmvc+hibernate的maven專案搭建
1.新建一個maven專案 (1)選擇工作區間 (2)選擇maven-archetype-webapp (3)輸入Group id(包名的字首)和Artifact Id(專案名),然後finish (4)完成上面的步驟,專案的目
spring+springMVC+hibernate 三大框架整合
首先我們要知道hibernate五大物件:,本例項通過深入的使用這五大物件和spring+springMVC相互結合,體會到框架的好處,提高我們的開發效率 Hibernate有五大核心介面,分別是:Session Transaction Query S
Spring+SpringMVC+hibernate整合開發
exp mvc margin tar e30 fio ilb fc14 h264 被瘟謎謫逼戲溫次蔡蒙磊疤回http://shequ.docin.com/vpe32249 空私錘氖園掠覆痔瓜傅殖http://jz.docin.com/gqsn83067 境噬栽品新嗚趙德
spring-springmvc-hibernate項目小結
-s factory 註意 org listener con erl listen load 1. web.xml中別忘記加入spring監聽器 <listener> <listener-class>org.springframe
OA——創建Spring+SpringMVC+Hibernate項目
libs 配置連接 jsp json數據 context http 事物 ons filter 1、創建maven webapp項目 2、書寫pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <projec
測試ssh框架搭建時遇到hibernate無法連線資料庫
問題提示 log4j:WARN No appenders could be found for logger (org.jboss.logging). log4j:WARN Please initialize the log4j system properly. log