Spring+Spring MVC+Hibernate增查(使用註解)

使用Spring+Spring MVC+Hibernate作增刪改查開發效率真的很高。使用Hibernate簡化了JDBC鏈接數據庫的的重複性代碼。下面根據本身作的一個簡單的增長和查詢,把一些難點分析出來:css

首先項目目錄結構:(Hibernate持久化數據鏈接信息交給Spring進行管理;別忘了加入Hibernate和Spring相關的架包.jar)html

第一步:弄個用戶實體類(配置Users.hbm.xml映射文件):java

 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 id
13      */
14     public int getId() {
15         return id;
16     }
17     /**
18      * @param id the id to set
19      */
20     public void setId(int id) {
21         this.id = id;
22     }
23     /**
24      * @return the username
25      */
26     public String getUsername() {
27         return username;
28     }
29     /**
30      * @param username the username to set
31      */
32     public void setUsername(String username) {
33         this.username = username;
34     }
35     /**
36      * @return the password
37      */
38     public String getPassword() {
39         return password;
40     }
41     /**
42      * @param password the password to set
43      */
44     public void setPassword(String password) {
45         this.password = password;
46     }
47     /**
48      * @return the sex
49      */
50     public String getSex() {
51         return sex;
52     }
53     /**
54      * @param sex the sex to set
55      */
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層(公共類)web

 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 @Transactional
19 public class IBaseDaoImpl<T> implements IBaseDao<T>{
20    
21     //注入sessionfactory
22     @Resource
23     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 stub
41         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 stub
64         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 stub
75         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 stub
85     sessionFactory.getCurrentSession().save(t);    
86     }
87 
88     public void update(T t) {
89         // TODO Auto-generated method stub
90         sessionFactory.getCurrentSession().update(t);
91     }
92 
93 }

第三步:Servse用戶邏輯層spring

 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.xmlsql

 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.xsd
10            http://www.springframework.org/schema/tx
11            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/tx
10            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>

第五步:註冊頁面:apache

 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="男" />&nbsp;<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>

註冊跳轉至處理頁:session

 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 Administrator
19  *
20  */
21 @org.springframework.stereotype.Controller
22 @RequestMapping("/userController")
23 public class UserController {
24     
25     //注入業務層
26     @Resource
27     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查詢全部用戶信息:mvc

 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="description" 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

若是須要轉載,請註明出處,謝謝!!
相關文章
相關標籤/搜索