美文网首页
JAVA Web学习(26)___Sping与Hibernate

JAVA Web学习(26)___Sping与Hibernate

作者: 岁月静好浅笑安然 | 来源:发表于2019-10-16 17:34 被阅读0次

    Sping与Hibernate整合批量添加数据 示例

    • 1.创建Web项目,引入以下jar包

    antlr-2.7.6.jar、asm.jar、cglib-2.1.3.jar、commons-collections-2.1.1.jar、commons-logging-1.0.4.jar
    dom4j-1.6.1.jar、ehcache-1.2.jar、hibernate3.jar、jstl-1.2.jar、jta.jar、log4j-1.2.11.jar、mysql-connector-java-5.1.10-bin.jar、mysql-connector-java-5.1.38.jar、slf4j-api-1.5.8.jar、slf4j-log4j12-1.5.8.jar、spring-aop-4.3.20.RELEASE.jar、spring-web.jar、spring-webmvc.jar、spring.jar

    • 2.创建javabean 类User.java
    public class User{
        
        private Integer id;//id值
    
        private String name;//用户名称
        
        private String business;//职务
        
        private Date addTime;//添加时间
    ...                                        //省略setter()和getter()方法
    }
    
    • 3.创建hibernate映射文件User.hbm.xml,此文件和User.java在同一个目录
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="com.mr.user.User" table="User">
            <!-- id值 -->
            <id name="id" column="id" type="int">
                <generator class="native"/>
            </id>
            <!-- 名称 -->
            <property name="name" type="string" length="45">
                <column name="name"/>
            </property>
            <!-- 职务 -->
            <property name="business" type="string" length="45">
                <column name="business"/>
            </property>
            <!-- 信息添加时间 -->
            <property name="addTime" type="java.util.Date">
                <column name="addTime"/>
            </property>
        </class>
    </hibernate-mapping>
    
    
    • 4.创建DAOSupport.java继承HibernateDaoSupport
    public class DAOSupport extends HibernateDaoSupport {
        public void InsertPatchInfo(int count,HttpServletRequest request,HttpServletResponse response){
            String name = request.getParameter("name");//用户名称
            String business = request.getParameter("business");//职务
            HibernateTemplate template = this.getHibernateTemplate();//实例化Hibernate模板
            for(int i = 0; i < count ; i++){//批量执行添加方法
                User userVO = new User();//实例化对象 
                userVO.setName(name+i);//设置用户名
                userVO.setBusiness(business);//设置职务
                userVO.setAddTime(new Date());//设置添加时间
                template.save(userVO);//执行添加方法
            }   
        }
    }
    
    
    • 5.创建批量添加信息的控制器AddUser.java 继承AbstractController
    public class AddUser extends AbstractController  {
        
        private DAOSupport dst;//注入DAOSupport
        
        public DAOSupport getDst() {
            return dst;
        }
    
        public void setDst(DAOSupport dst) {
            this.dst = dst;
        }
    
        protected ModelAndView handleRequestInternal(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            //添加信息的条数
            request.setCharacterEncoding("UTF-8");
            int count = Integer.parseInt(request.getParameter("count"));
            dst.InsertPatchInfo(count,request,response);//执行封装的批量添加方法
            Map map = new HashMap();//定义映射
            //设置添加成功时的提示信息
            map.put("succ", "信息添加成功,共添加"+count+"条信息!");
            return new ModelAndView("index",map);
        }
    }
    
    
    • 6.创建applicationContext.xml,在/WEB-INF/根目录下
    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
        <!-- 配置数据源 -->
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName">
                <value>com.mysql.jdbc.Driver</value>
            </property>
            <property name="url">
            <!-- ?characterEncoding=utf-8这样可以解决乱码 -->
                <value>jdbc:mysql://localhost:3306/db_database13?characterEncoding=utf-8
                </value>
            </property>
            <property name="username">
                <value>root</value>
            </property>
            <property name="password">
                <value>hwp123456</value>
            </property>
        </bean>
        <!-- 定义Hibernate的sessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource">
                <ref bean="dataSource" />
            </property>
            <property name="hibernateProperties">
                <props>
                    <!-- 数据库连接方言 -->
                    <prop key="dialect">org.hibernate.dialect.SQLServerDialect</prop>
                    <!-- 在控制台输出SQL语句 -->
                    <prop key="hibernate.show_sql">true</prop>
                    <!-- 格式化控制台输出的SQL语句 -->
                    <prop key="hibernate.format_sql">true</prop>
                </props>
            </property>
            <!--hibernate映射文件 -->
            <property name="mappingResources">
                <list>
                    <value>com/mr/user/User.hbm.xml</value>
                </list>
            </property>
        </bean> 
        <!-- 为DAOSupport注入sessionFactory -->
        <bean id="dao" class="com.mr.dao.DAOSupport">
            <property name="sessionFactory">
                <ref local="sessionFactory"/>
            </property>
        </bean>
        <!--定义控制器转发视图类 -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
        <!-- 映射的do -->
        <bean name="/save.do" class="com.mr.main.AddUser">
            <property name="dst">
                <ref local="dao"/>
            </property>
        </bean>
    </beans>
    
    • 7.编辑index.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%
        String path = request.getContextPath();
        request.setAttribute("ContextPath", path);
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>批量添加信息</title>
    </head>
    <body>
    <div id="main">
    <form action="${ContextPath}/save.do" method="post">
    <br />
    <table>
        <tr>
            <td width="120px" class="td_pad">用户名称:</td>
            <td><input type="text" name="name" value="" /></td>
        </tr>
        <tr>
            <td width="120px" class="td_pad">职务:</td>
            <td><input type="text" name="business" value="" /></td>
        </tr>
        <tr>
            <td width="120px" class="td_pad">添加信息数量:</td>
            <td><input type="text" name="count" value="" /></td>
        </tr>
        <tr>
            <td align="center" colspan="2" class="td_pad">
            <input type="submit" value="添加" /> &nbsp;&nbsp; <input type="reset"
                value="取消" /></td>
        </tr>
    </table>
    </form>
    </div>
    <!-- 信息添加成功后的提示信息 -->
    <script type="text/javascript">
            <c:if test="${succ!=null}">
                alert("${succ}");
            </c:if> 
    </script>
    </body>
    </html>
    
    • 8.配置web.xml
    <?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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
    </web-app>
    
    • 9.数据库DDL,数据库名字db-database,表名字User数据库库账号和密码要根据实际设置
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(45) DEFAULT NULL,
      `business` varchar(45) DEFAULT NULL,
      `addTime` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    

    相关文章

      网友评论

          本文标题:JAVA Web学习(26)___Sping与Hibernate

          本文链接:https://www.haomeiwen.com/subject/jdmumctx.html