首页 > 学院 > 开发设计 > 正文

Spring+SpringMVC+Hibernate增查(使用注解)

2019-11-14 15:37:05
字体:
来源:转载
供稿:网友

使用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="男" />&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>

注册跳转至处理页:

 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="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如果需要转载,请注明出处,谢谢!!

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表