使用SPRing+Spring MVC+Hibernate做增刪改查開發效率真的很高。使用Hibernate簡化了JDBC連接數據庫的的重復性代碼。下面根據自己做的一個簡單的增加和查詢,把一些難點分析出來:
首先項目目錄結構:(Hibernate持久化數據連接信息交給Spring進行管理;別忘了加入Hibernate和Spring相關的架包.jar)
第一步:弄個用戶實體類(配置Users.hbm.xml映射文件):
1 package com.ssh.SpringMVC.enity; 2 3 4 5 public class Users { 6 7 private int id;//id 8 private String username;//用戶名 9 private String passWord;//密碼10 private String sex;//性別11 /**12 * @return the id13 */14 public int getId() {15 return id;16 }17 /**18 * @param id the id to set19 */20 public void setId(int id) {21 this.id = id;22 }23 /**24 * @return the username25 */26 public String getUsername() {27 return username;28 }29 /**30 * @param username the username to set31 */32 public void setUsername(String username) {33 this.username = username;34 }35 /**36 * @return the password37 */38 public String getPassword() {39 return password;40 }41 /**42 * @param password the password to set43 */44 public void setPassword(String password) {45 this.password = password;46 }47 /**48 * @return the sex49 */50 public String getSex() {51 return sex;52 }53 /**54 * @param sex the sex to set55 */56 public void setSex(String sex) {57 this.sex = sex;58 }59 60 }
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 7 <hibernate-mapping 8 package="com.ssh.SpringMVC.enity"> 9 10 <class name="Users" table="t_users">11 <id name="id">12 <generator class="increment"/>13 </id>14 <property name="username" />15 <property name="password"/>16 <property name="sex"/>17 </class>18 19 20 </hibernate-mapping>
第二步:建個Dao層(公共類)
1 package com.ssh.SpringMVC.Dao; 2 3 import java.util.List; 4 5 /* 6 * 公共類 7 */ 8 public interface IBaseDao<T> { 9 //保存對象10 public void save(T t);11 //刪除對象12 public void delete(int id);13 //更新對象14 public void update(T t);15 //根據id查詢對象16 public T getObjectByid(int id);17 //查詢所有對象18 public List<T> getObjectALL();19 //根據一組id查詢一組對象20 public List<T> getObjectByids(int ids);21 22 }
1 package com.ssh.SpringMVC.Dao.Impl; 2 3 import java.lang.reflect.ParameterizedType; 4 import java.util.List; 5 6 import javax.annotation.Resource; 7 8 import org.hibernate.sessionFactory; 9 10 import org.springframework.transaction.annotation.Transactional;11 12 import com.ssh.SpringMVC.Dao.IBaseDao;13 14 /*15 * 公共方法實現類16 */17 @SuppressWarnings("unchecked")18 @Transactional19 public class IBaseDaoImpl<T> implements IBaseDao<T>{20 21 //注入sessionfactory22 @Resource23 SessionFactory sessionFactory;24 Class clazz;25 26 27 //構造方法:獲取T的真實類型28 public IBaseDaoImpl(){29 ParameterizedType pType=(ParameterizedType) this.getClass().getGenericSuperclass();30 clazz=(Class) pType.getActualTypeArguments()[0];31 System.out.print(clazz.getSimpleName());32 33 }34 /*35 * 刪除對象36 * (non-Javadoc)37 * @see com.ssh.SpringMVC.Dao.IBaseDao#delete(int)38 */39 public void delete(int id) {40 // TODO Auto-generated method stub41 sessionFactory.getCurrentSession().delete(42 sessionFactory.getCurrentSession().get(clazz, id)); 43 }44 45 /*46 * 查詢所有對象47 * (non-Javadoc)48 * @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectALL()49 */50 51 public List<T> getObjectALL() {52 // System.out.println("=====:"+"from"+clazz.getSimpleName());53 // System.out.println("=====:"+"from "+clazz.getSimpleName());54 // System.out.println("--------------"+clazz.getSimpleName());55 return sessionFactory.getCurrentSession().createQuery("from "+clazz.getSimpleName()).list();56 }57 /*58 * 根據id獲取對象59 * (non-Javadoc)60 * @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectByid(int)61 */62 public T getObjectByid(int id) {63 // TODO Auto-generated method stub64 return (T) sessionFactory.getCurrentSession().get(clazz, id);65 }66 67 68 /*69 * 根據一組id獲取一組對象70 * (non-Javadoc)71 * @see com.ssh.SpringMVC.Dao.IBaseDao#getObjectByids(int)72 */73 public List<T> getObjectByids(int ids) {74 // TODO Auto-generated method stub75 return sessionFactory.getCurrentSession().createQuery(76 "from"+clazz.getSimpleName()+"where id in(:ids)").setParameter("ids", ids).list();77 }78 /*79 * 保存對象80 * (non-Javadoc)81 * @see com.ssh.SpringMVC.Dao.IBaseDao#save(java.lang.Object)82 */83 public void save(T t) {84 // TODO Auto-generated method stub85 sessionFactory.getCurrentSession().save(t); 86 }87 88 public void update(T t) {89 // TODO Auto-generated method stub90 sessionFactory.getCurrentSession().update(t);91 }92 93 }
第三步:Servse用戶邏輯層
1 package com.ssh.SpringMVC.Servse; 2 3 import com.ssh.SpringMVC.Dao.IBaseDao; 4 import com.ssh.SpringMVC.enity.Users; 5 6 /* 7 * 用戶邏輯層 8 */ 9 10 public interface IUserService extends IBaseDao<Users>{11 //定義特有方法。。。12 }
1 package com.ssh.SpringMVC.Servse.Impl; 2 3 import org.springframework.stereotype.Service; 4 5 import com.ssh.SpringMVC.Dao.Impl.IBaseDaoImpl; 6 import com.ssh.SpringMVC.Servse.IUserService; 7 import com.ssh.SpringMVC.enity.Users; 8 /* 9 * 用戶實現類10 * 11 */12 @Service("userService")13 public class IUserServiceImpl extends IBaseDaoImpl<Users> implements IUserService{14 15 }
第四步:配置applicationContext.xml和springmvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-2.5.xsd10 http://www.springframework.org/schema/tx11 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">12 13 14 15 <!-- 引入外部配置文件 -->16 <context:property-placeholder location="classpath:Oracle.properties" />17 18 <!-- 配置數據源(將所有的配置寫在Spirng中) -->19 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">20 21 <!-- 數據庫連接信息 -->22 <property name="url" value="${url}" />23 <property name="username" value="${username}" />24 <property name="password" value="${password}" />25 <property name="driverClassName" value="${driverClassName}" />26 27 <!-- 最大連接數 -->28 <property name="maxActive" value="${maxActive}" />29 <!-- 最大空閑數 -->30 <property name="maxIdle" value="${maxIdle}" />31 <!--最小空閑數-->32 <property name="minIdle" value="${minIdle}" />33 <!-- 初始連接數 -->34 <property name="initialSize" value="${initialSize}" />35 36 </bean>37 38 <!-- 創建sessionFactory -->39 <bean id="sessionFactory"40 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">41 <property name="dataSource" ref="dataSource" />42 43 44 <!-- 配置Hibernate配置信息 -->45 <property name="hibernateProperties">46 <props>47 <prop key="hibernate.show_sql">true</prop>48 <prop key="hibernate.hbm2ddl.auto">update</prop>49 <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>50 </props>51 </property>52 53 <!-- 配置實體類映射信息 -->54 <property name="mappingResources">55 <list>56 57 <value>com/ssh/SpringMVC/enity/Users.hbm.xml</value>58 59 </list>60 </property>61 62 </bean>63 64 <!-- 配置事務管理器 -->65 <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">66 <property name="sessionFactory" ref="sessionFactory"/>67 </bean>68 69 70 71 </beans>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-2.5.xsd 9 http://www.springframework.org/schema/tx10 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">11 12 <!-- SpringMVC的配置規則和Spring是一樣的:無縫集成 -->13 <!-- 配置掃描器;自動裝配 -->14 <context:component-scan base-package="com.ssh.SpringMVC" />15 16 <!-- 注解事務配置 -->17 <tx:annotation-driven transaction-manager="transactionManager" />18 19 <!-- 配置視圖 -->20 <bean id="internalView"21 class="org.springframework.web.servlet.view.InternalResourceViewResolver">22 <!-- 配置視圖前綴 -->23 24 <property name="prefix" value="/" />25 <!-- 配置視圖后綴 -->26 <property name="suffix" value=".jsp" />27 </bean>28 29 30 </beans>
web.xml配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 8 <!-- spring監聽器: --> 9 <listener>10 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>11 12 </listener>13 14 <!-- 指定spring文件路徑 -->15 <context-param>16 <param-name>contextConfigLocation</param-name>17 <param-value>classpath:applicationContext.xml</param-value>18 </context-param>19 20 <!-- =====================配置spring mvc Start================================= -->21 <servlet>22 <servlet-name>SpringMVC</servlet-name>23 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>24 25 <!--配置springmvc路勁-->26 <init-param>27 <param-name>contextConfigLocation</param-name>28 <param-value>classpath:springmvc.xml</param-value>29 </init-param>30 <!-- >=0代表web容器啟動的時候加載servlet(數字代表優先級) -->31 <load-on-startup>1</load-on-startup>32 </servlet>33 34 <servlet-mapping>35 <servlet-name>SpringMVC</servlet-name>36 <url-pattern>/</url-pattern>37 38 </servlet-mapping>39 40 <!-- 配置編碼過濾器 -->41 <filter>42 <filter-name>encoding</filter-name>43 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>44 <init-param>45 <param-name>encoding</param-name>46 <param-value>utf-8</param-value>47 </init-param>48 <init-param>49 <param-name>forceEncoding</param-name>50 <param-value>true</param-value>51 </init-param>52 </filter>53 <filter-mapping>54 <filter-name>encoding</filter-name>55 <url-pattern>/*</url-pattern>56 </filter-mapping>57 58 59 60 <welcome-file-list>61 <welcome-file>index.jsp</welcome-file>62 </welcome-file-list>63 </web-app>
第五步:注冊頁面:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head>10 <base href="<%=basePath%>">11 12 <title>用戶注冊</title>13 14 15 </head>16 17 <body>18 <form action="userController?add" method="post">19 <table>20 <tr>21 <td>用戶名:</td>22 <td><input type="text" name="username" /></td>23 </tr>24 <tr>25 <td>密碼:</td>26 <td><input type="text" name="password" /></td>27 </tr>28 <tr>29 <td>性別:</td>30 <td><input type="radio" name="sex" value="男" />男 <input type="radio" name="sex" value="女" />女</td>31 </tr>32 <tr>33 <td></td>34 <td><input type="submit" /></td>35 </tr>36 37 38 </table>39 40 </form>41 </body>42 </html>
注冊跳轉至處理頁:
1 package com.ssh.SpringMVC.controller; 2 3 4 import java.util.List; 5 6 import javax.annotation.Resource; 7 8 9 import org.springframework.web.bind.annotation.RequestMapping;10 import org.springframework.web.servlet.ModelAndView;11 12 13 import com.ssh.SpringMVC.Servse.IUserService;14 import com.ssh.SpringMVC.enity.Users;15 16 /**17 * 控制層18 * @author Administrator19 *20 */21 @org.springframework.stereotype.Controller22 @RequestMapping("/userController")23 public class UserController {24 25 //注入業務層26 @Resource27 IUserService userService;28 /*29 * 添加用戶30 */31 @RequestMapping(params="add")32 public String add(Users user){33 userService.save(user);34 35 return "redirect:userController?all";36 37 }38 /*39 * 查詢所有對象40 */41 @RequestMapping(params="all")42 public ModelAndView all(){43 44 //list集合45 List<Users> li=userService.getObjectALL();46 47 return new ModelAndView("index","userLi",li);48 }49 }
然后跳轉至index.jsp查詢所有用戶信息:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html>10 <head>11 <base href="<%=basePath%>">12 13 <title>My JSP 'index.jsp' starting page</title>14 <meta http-equiv="pragma" content="no-cache">15 <meta http-equiv="cache-control" content="no-cache">16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">18 <meta http-equiv="descr content="This is my page">19 <!--20 <link rel="stylesheet" type="text/CSS" href="styles.css">21 -->22 </head>23 24 <body>25 <table border="1" cellpadding="10" cellspacing="0">26 <tr>27 <th>id</th>28 <th>姓名</th>29 <th>密碼</th>30 <th>性別</th>31 </tr>32 <c:forEach items="${userLi}" var="li">33 <tr>34 <td>${li.id}</td>35 <td>${li.username}</td>36 <td>${li.password}</td>37 <td>${li.sex}</td>38 </tr>39 </c:forEach>40 </table>41 42 </body>43 </html>
陷阱先知:
本人在做查詢的時候犯了個嚴重的不細心的問題:錯誤如下:
因為這個錯糾結了一個多小時。原因是什么,看下圖就明白了:
查詢語句忘記了打空格,本來查詢from Users,結果from Users合成一個fromUsers,才出現上面的錯,都是不細心造成的,謹記,下次務犯。
您可以通過點擊 右下角 的按鈕 來對文章內容作出評價, 也可以通過左下方的 關注按鈕 來關注我的博客的最新動態。 如果文章內容對您有幫助, 不要忘記點擊右下角的 推薦按鈕 來支持一下哦 如果您對文章內容有任何疑問, 可以通過評論或發郵件的方式聯系我: 2276292708@QQ.com或加入JAVA技術交流群:306431857如果需要轉載,請注明出處,謝謝??!
新聞熱點
疑難解答