SpringMVC+Spring+Hibernate的小例子,springmvchibernate

來源:互聯網
上載者:User

SpringMVC+Spring+Hibernate的小例子,springmvchibernate

Strusts2+Spring+Hibernate雖然是主流的WEB開發架構,但是SpringMVC有越來越多的人使用了,確實也非常好用,用得爽!

這裡實現了一個SpringMVC+Spring+Hibernate的小例子。注釋都在代碼裡面。

項目各包的結構如:



1, 首先是pom.xml

<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>com.miquan</groupId><artifactId>springmvc_spring_hibernate</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>springmvc_spring_hibernate Maven Webapp</name><url>http://maven.apache.org</url><dependencies><!-- expectj --><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.0.4.RELEASE</version></dependency><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.1.0.RELEASE</version></dependency><dependency><groupId>org.springframework.ws</groupId><artifactId>spring-ws-core</artifactId><version>2.2.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>4.1.1.RELEASE</version></dependency><!-- hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>4.3.6.Final</version></dependency><!-- dbcp --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><!-- MYSQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.18</version></dependency></dependencies><build><finalName>springmvc_spring_hibernate</finalName></build></project>

2, web.xml配置好SpringMVC和Spring

<?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_3_0.xsd"id="WebApp_ID" version="3.0"><!-- Spring配置。(必須配,要不會找不到bean) -->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener><!-- spring mvc (系統在啟動的時候會根據springmvc-servlet中的配置找到所有的controller並初始化)--><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern><!-- 這裡不能加* --></servlet-mapping></web-app>

3, SpringMVC的配置——springmvc-servlet.xml(注意命名,對應servlet中的springmvc)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:p="http://www.springframework.org/schema/p"    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        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd"        >            <!-- 存在controller的包。注意這裡寫的是包名,不是類名 -->    <context:component-scan base-package="com.miquan.controller"/><mvc:annotation-driven /><!-- 靜態檔案 --><mvc:resources location="/res/" mapping="/res/**"></mvc:resources><!-- 跳轉檔案的前尾碼 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/view/"></property><property name="suffix" value=".jsp"></property></bean></beans>

4, spring的配置——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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation=" http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd         http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd           http://www.springframework.org/schema/tx           http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 自動掃面註解包 --><context:annotation-config /><context:component-scan base-package="com.miquan.*" /><!-- 資料來源 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://127.0.0.1:3306/ssh" /><property name="username" value="root" /><property name="password" value="root" /></bean><!-- 配置sessionFactory --><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="packagesToScan" value="com.miquan.model" /><!-- 實體類的包 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop><!-- 會自動創表,但是不會自動建立資料庫,所以要先建立資料庫。 --><prop key="hibernate.hbm2ddl.auto">update</prop><prop key="hibernate.format_sql">true</prop></props></property></bean><!-- 用於注入到GeneralDao中 --><bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 配置交易管理 --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 開啟交易管理註解 --><aop:aspectj-autoproxy /><tx:annotation-driven /></beans>

5, 實體類。

package com.miquan.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Entity@Tablepublic class User {private int id;private String username;private String password;public User() {super();}public User(int id, String username, String password) {super();this.id = id;this.username = username;this.password = password;}@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", password="+ password + "]";}}

6, controller層。

package com.miquan.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.miquan.model.User;import com.miquan.service.IUserService;@Controller@RequestMapping(value="/user")public class UserController {/** * 注入userService。 * 如果userService繼承了某個介面, * 這裡類型必須是介面IUserService, * 不能是類UserService,不知道為什麼。 */@Autowiredprivate IUserService userService;@RequestMapping(value="/registe", method=RequestMethod.GET)public String registe() {User user = new User(0, "梁國俏", "999");userService.registe(user);return "index";}}

7, service層。

package com.miquan.service;import com.miquan.model.User;public interface IUserService {public boolean registe(User user);}

package com.miquan.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.miquan.dao.IGeneralDao;import com.miquan.model.User;@Servicepublic class UserService implements IUserService {@Autowiredprivate IGeneralDao generalDao;/*  * 這裡要有事務註解,預設readOnly=true,不設定的話會報錯。 * insert和update操作都要。 */@Transactional(readOnly=false)public boolean registe(User user) {generalDao.save(user);return false;}}

8, dao層。

package com.miquan.dao;import java.io.Serializable;import java.util.List;public interface IGeneralDao {public <T> T findById(Class<T> type, Serializable id);        public <T> List<T> findAll(Class<T> type);        public void save(Object... entities);        public void update(Object... entities);        public void saveOrUpdate(Object entity);        public void delete(Object... entities);        public void deleteById(Class<?> type, Serializable id);        public void refresh(Object... entities);        public void flush();}

package com.miquan.dao;import java.io.Serializable;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.orm.hibernate4.HibernateTemplate;import org.springframework.stereotype.Repository;/** * 這個類將dao成封裝成了一個操作類,從網上複製過來的。 */@Repositorypublic class GeneralDao implements IGeneralDao {/** * 這個bean裡面需要注入sessionFactory,所以把這個bean寫在了配置中。 */@Autowiredprivate HibernateTemplate hibernateTemplate;public <T> T findById(Class<T> type, Serializable id) {return hibernateTemplate.get(type, id);}public <T> List<T> findAll(Class<T> type) {return hibernateTemplate.loadAll(type);}public void save(Object... entities) {for (Object entity : entities) {hibernateTemplate.save(entity);}}public void saveOrUpdate(Object entity) {hibernateTemplate.saveOrUpdate(entity);}public void update(Object... entities) {for (Object entity : entities) {hibernateTemplate.update(entity);}}public void delete(Object... entities) {for (Object entity : entities) {if (entity != null) {hibernateTemplate.delete(entity);}}}public void deleteById(Class<?> type, Serializable id) {if (id == null) {return;}Object entity = findById(type, id);if (entity == null) {return;}delete(entity);}public void refresh(Object... entities) {for (Object entity : entities) {hibernateTemplate.refresh(entity);}}public void flush() {hibernateTemplate.flush();}}

9, 測試。

package com.miquan.service;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import com.miquan.controller.UserController;public class UserServiceTest {@Testpublic void test() {ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");UserController controller = ctx.getBean(UserController.class);controller.registe();}}

或者部署在tomcat上,在瀏覽器訪問http://localhost:8080/xx項目/user/registe。


java用spring mvc + hibernate,實現資料庫的增刪改查

1)在applicationContext裡面配置Hibernate的dataSource和SessionFactory
2)編寫Dao的介面是實作類別。如果用到Spring的Hibernate的操作模板(HibernateTemplate)可以繼承HibernateDaoSupport,實作類別註解成@Repository
3)編寫Action,然後註解成@Controller,在Action裡面需要用@Autowired注入Dao的執行個體
4)配置applicationContext.xml,加上Spring MVC的視圖處理器
5)編寫頁面,然後提交請求。搞定!
 
JAVA用springMVC+hibernate做的需要串連資料庫的簡單的增刪改查的小程式

這個非常簡單,Spring官方提供很多樣本,簡單的寵物商店等,你可以到spring官網,下載spring roo這個工具 ,安裝後它的smaple目錄有很多樣本,你把樣本指令碼執行一次,就自動產生spring mvc的樣本程式,如果你不想使用樣本,你可以使用spring roo工具根據提示,自動建立spring mvc的增刪改查小程式。

非常簡單哦,只需要根據spring roo的嚮導提示進行就可以快速的建立spring mvc程式。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.