首页 > 代码库 > 06_MyBatis,Spring,SpringMVC整合

06_MyBatis,Spring,SpringMVC整合


  1. 项目结构

技术分享

技术分享

技术分享

  1. Spring的配置:

beans.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:mvc="http://www.springframework.org/schema/mvc"

   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/mvc

      http://www.springframework.org/schema/mvc/spring-mvc-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-3.0.xsd ">                     

      

      <context:component-scanbase-package="com.rl"/>

      

      <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">

          <propertyname="driverClassName"value="com.mysql.jdbc.Driver"></property>

          <propertyname="url"value="jdbc:mysql://localhost:3306/mybatis"></property>

          <propertyname="username"value="root"></property>

          <propertyname="password"value="123456"></property>

      </bean>

      

      <!--

          使用spring来管理sqlSessionFactory

       -->

      <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

          <propertyname="configLocation"value="classpath:sqlMapConfig.xml"></property>

          <propertyname="dataSource"ref="dataSource"></property>

      </bean>

      

      <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

          <propertyname="dataSource"ref="dataSource"></property>

      </bean>

      

      <tx:adviceid="txAdvice"transaction-manager="txManager">

          <tx:attributes>

             <tx:methodname="save*"propagation="REQUIRED"/>

             <tx:methodname="update*"propagation="REQUIRED"/>

             <tx:methodname="delete*"propagation="REQUIRED"/>

             <tx:methodname="select*"read-only="true"/>

          </tx:attributes>

      </tx:advice>

      

      <aop:config>

          <aop:advisoradvice-ref="txAdvice"pointcut="execution(* com.rl.service..*.*(..))"/>

      </aop:config>

</beans>

  1. springmvc.xml的配置内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:mvc="http://www.springframework.org/schema/mvc"

   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/mvc

      http://www.springframework.org/schema/mvc/spring-mvc-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-3.0.xsd ">                      

      

      <context:component-scanbase-package="com.rl.controller"/>

      <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">

          <propertyname="prefix"value="/WEB-INF/jsp/"></property>

          <propertyname="suffix"value=".jsp"></property>

      </bean>

</beans>

  1. web.xml的配置内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

   id="WebApp_ID"version="2.5">

   

   <listener>

      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

   </listener>

   <context-param>

      <param-name>contextConfigLocation</param-name>

      <param-value>classpath:beans.xml</param-value>

   </context-param>

   

   <servlet>

      <servlet-name>springmvc</servlet-name>

      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

      <init-param>

          <param-name>contextConfigLocation</param-name>

          <param-value>classpath:springmvc.xml</param-value>

      </init-param>

   </servlet>

   <servlet-mapping>

      <servlet-name>springmvc</servlet-name>

      <url-pattern>*.do</url-pattern>

   </servlet-mapping>

   

   <filter>

       <filter-name>SpringCharacterEncodingFilter</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

       <init-param>

           <param-name>encoding</param-name>

           <param-value>UTF-8</param-value>

       </init-param>

   </filter>

   <filter-mapping>

       <filter-name>SpringCharacterEncodingFilter</filter-name>

       <url-pattern>*.do</url-pattern>

   </filter-mapping>

   

</web-app>

5 log4j.properties

log4j.rootLogger=DEBUG,Console

#Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=%d[%t]%-5p[%c]-%m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

  1. sqlMapConfig.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEconfiguration

PUBLIC"-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

  <typeAliases>

     <typeAliastype="com.rl.model.Person"alias="person"/>

  </typeAliases>

  <mappers>

     <mapperresource="com/rl/mapper/PersonMapper.xml"/>

  </mappers>

</configuration>

PersonMapper.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEmapper

PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--

namespace:命名空间,用来唯一标识一个映射文件,命名规范就是当前的文件的包加上文件名

 -->

<mappernamespace="com.rl.mapper.PersonMapper">

 

  <resultMaptype="person"id="BaseResultMap">

     <!--

        column:库表的字段

        property:库表所有映射的实体类中属性名

      -->

     <idcolumn="person_id"property="personId"/>

     <resultcolumn="name"property="name"/>

     <resultcolumn="gender"property="gender"/>

     <resultcolumn="person_addr"property="personAddr"/>

     <resultcolumn="birthday"property="birthday"/>

  </resultMap>

  

  <!--

     公用的sql片段,也可以接收参数动态sql,所有的sql可以

   -->

  <sqlid="columns">

     PERSON_ID, NAME, GENDER, PERSON_ADDR, BIRTHDAY

  </sql>

  

  <!--

     根据id来查询一个Person的数据

     sql语句接收参数的一个语法#{},如果接收的是一个{}中的内容任意select * from person_test t where t.ID = ?,使用预编译方式生成sql

     id:sql语句的唯一的标识不能重复

     parameterType:sql要接收的数据类型

     resultTypesql所返回的数据类型

   -->

   

   <!--

     实际项目中数据库的表的字段一般由多个单词来构成由下划线来分隔多个单词 person_addr

     javamodel的实体类中的属性多个单词的命名规范是驼峰模式personAddr

    -->

    <!--

      useCache:控制当前的这个sql是否使用二级缓存

     -->

   <selectid="selectPersonById"parameterType="int"resultMap="BaseResultMap"useCache="true">

     select * from person t where t.person_id = #{id}

   </select>

   

  <!--库表变更 -->

  <insertid="insert"parameterType="person">

     

     <selectKeykeyProperty="personId"order="AFTER"resultType="int">

        select LAST_INSERT_ID()

     </selectKey>

     insert into person (person_id, name, gender, person_addr, birthday)

     values(#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday})

  </insert>

  

  

  <!--

     删除的sql不能使用别名

   -->

  <deleteid="delete"parameterType="int">

     delete from person where person_id = #{personId}

  </delete>

  

  <!--动态sql -->

  <!--

     map.put("name", "");

     map.put("gender", "0");

     map.put("personAddr", "东京")

     map.put("birthday", new Date());

     

     <where>会自动处理and第一个and可以不写,其他的and必须要写

   -->

  <selectid="selectPersonByCondition"parameterType="map"resultMap="BaseResultMap">

     select * from person t

     <where>

        <iftest="name != null">

            t.name like ‘%${name}%‘

        </if>

        <iftest="gender != null">

           and t.gender = #{gender}

        </if>

        <iftest="personAddr != null">

           and t.person_addr like ‘%${personAddr}%‘

        </if>

        <iftest="birthday != null">

           <![CDATA[

               and t.birthday < #{birthday}

           ]]>

        </if>

     </where>

  </select>

  

  

  <!--

     动态修改

     <set>标签可以去掉最后一个逗号

     

     flushCache:二级缓存的刷新的配置:默认是true:会刷新,如果false就不刷新缓存

   -->

  <updateid="dynamicUpdate"parameterType="person"flushCache="false">

     update person t

     <set>

        <iftest="name != null">

           t.name = #{name},

        </if>

        <iftest="gender != null">

           t.gender = #{gender},

        </if>

        <iftest="personAddr != null">

           t.person_addr = #{personAddr},

        </if>

        <iftest="birthday != null">

           t.birthday = #{birthday}

        </if>

     </set>

     where t.person_id = #{personId}

  </update>

  

</mapper>

6 Person.java的内容如下:

package com.rl.model;

 

import java.io.Serializable;

import java.util.Date;

 

public class Person implements Serializable{

        private static final long serialVersionUID = 7728191033619971201L;

        private Integer personId;

        private String name;

        private String gender;

        private String personAddr;

        private Date birthday;

        

        public Integer getPersonId() {

                  return personId;

        }

 

        public void setPersonId(Integer personId) {

                  this.personId = personId;

        }

 

        public String getName() {

                  return name;

        }

 

        public void setName(String name) {

                  this.name = name;

        }

 

        public String getGender() {

                  return gender;

        }

 

        public void setGender(String gender) {

                  this.gender = gender;

        }

 

        public String getPersonAddr() {

                  return personAddr;

        }

 

        public void setPersonAddr(String personAddr) {

                  this.personAddr = personAddr;

        }

 

        public Date getBirthday() {

                  return birthday;

        }

 

        public void setBirthday(Date birthday) {

                  this.birthday = birthday;

        }

}

7 PersonDao.java

package com.rl.dao;

 

import java.util.List;

import java.util.Map;

 

import com.rl.model.Person;

 

public interface PersonDao {

        public void save(Person person);

        public Person selectPersonById(Integer personId);

        public void update(Person person);

        public void delete(Integer personId);

        public List<Person> selectPersonByCondition(Map<String, Object> map);

}

8 PersonDaoImpl.java的内容如下:

package com.rl.dao.impl;

 

import java.util.List;

import java.util.Map;

 

import org.mybatis.spring.support.SqlSessionDaoSupport;

import org.springframework.stereotype.Repository;

 

import com.rl.dao.PersonDao;

import com.rl.model.Person;

@Repository

public class PersonDaoImpl extends SqlSessionDaoSupport implements PersonDao {

        //命名空间

        String ns = "com.rl.mapper.PersonMapper.";

        @Override

        public void save(Person person) {

                  this.getSqlSession().insert(ns+"insert", person);

        }

 

        @Override

        public Person selectPersonById(Integer personId) {

                  return (Person) this.getSqlSession().selectOne(ns+"selectPersonById", personId);

        }

 

        @Override

        public void update(Person person) {

                  this.getSqlSession().update(ns+"dynamicUpdate", person);

        }

 

        @Override

        public void delete(Integer personId) {

                  this.getSqlSession().delete(ns+"delete", personId);

        }

 

        @SuppressWarnings("unchecked")

        @Override

        public List<Person> selectPersonByCondition(Map<String, Object> map) {

                  return this.getSqlSession().selectList(ns+"selectPersonByCondition", map);

        }

 

}

9 PersonService.java

package com.rl.service;

 

import java.util.List;

import java.util.Map;

 

import com.rl.model.Person;

 

public interface PersonService {

        public void save(Person person);

        public Person selectPersonById(Integer personId);

        public void update(Person person);

        public void delete(Integer personId);

        public List<Person> selectPersonByCondition(Map<String, Object> map);

}

10 PersonServiceImpl.java

package com.rl.service.impl;

 

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.rl.dao.PersonDao;

import com.rl.model.Person;

import com.rl.service.PersonService;

@Service

public class PersonServiceImpl implements PersonService {

 

        @Autowired

        private PersonDao personDao;

        

        @Override

        public void save(Person person) {

                  personDao.save(person);

        }

 

        @Override

        public Person selectPersonById(Integer personId) {

                  return personDao.selectPersonById(personId);

        }

 

        @Override

        public void update(Person person) {

                  personDao.update(person);

        }

 

        @Override

        public void delete(Integer personId) {

                  personDao.delete(personId);

        }

 

        @Override

        public List<Person> selectPersonByCondition(Map<String, Object> map) {

                  return personDao.selectPersonByCondition(map);

        }

}

11 PersonController.java的内容如下:

package com.rl.controller;

 

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.propertyeditors.CustomDateEditor;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.ServletRequestDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import org.springframework.web.bind.annotation.RequestMapping;

 

import com.rl.model.Person;

import com.rl.service.PersonService;

 

@Controller

@RequestMapping("/person")

public class PersonController {

        

        @Autowired

        private PersonService personService;

        

        /**

         * 跳转到添加页面

         */

        @RequestMapping("/toSave.do")

        public String toSave(){

                  return "add";

        }

        

        /**

         * 添加Person

         */

        @RequestMapping("/save.do")

        public String save(Person person){

                  personService.save(person);

                  return "redirect:listPerson.do";

        }

        

        /**

         * 查询Person

         */

        @RequestMapping("/getPerson.do")

        public String getPerson(Integer personId, Model model){

                  Person person = personService.selectPersonById(personId);

                  model.addAttribute("person", person);

                  return "update";

        }

        /**

         * 修改Person

         */

        @RequestMapping("/update.do")

        public String update(Person person){

                  personService.update(person);

                  return "redirect:listPerson.do";

        }

        

        /**

         * 删除

         */

        @RequestMapping("/delete.do")

        public String delete(Integer personId){

                  personService.delete(personId);

                  return "redirect:listPerson.do";

        }

 

        /**

         * 动态条件组合查询

         */

        @RequestMapping("/listPerson.do")

        public String listPerson(String name, String gender,

                           String personAddr, Date birthday, Model model){

                  Map<String, Object> map = new HashMap<String,Object>();

                  if(name != null && "".equals(name.trim())){

                           name = null;

                  }

                  if(gender != null && "".equals(gender.trim())){

                           gender = null;

                  }

                  if(personAddr != null && "".equals(personAddr.trim())){

                           personAddr = null;

                  }

                  map.put("name", name);

                  map.put("gender", gender);

                  map.put("personAddr", personAddr);

                  map.put("birthday", birthday);

                  List<Person> pList = personService.selectPersonByCondition(map);

                  model.addAttribute("pList", pList);

                  model.addAttribute("name", name);

                  model.addAttribute("gender", gender);

                  model.addAttribute("personAddr", personAddr);

                  model.addAttribute("birthday", birthday);

                  

                  return "list";

        }

        

        @InitBinder

        public void initBinder(ServletRequestDataBinder binder){

                  binder.registerCustomEditor(Date.class,

                                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));

        }

}

12 add.jsp

<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@tagliburi="http://java.sun.com/jsp/jstl/fmt" prefix="f"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <basehref="<%=basePath%>">

   

   <title>My JSP ‘list.jsp‘ starting page</title>

   

  <metahttp-equiv="pragma"content="no-cache">

  <metahttp-equiv="cache-control"content="no-cache">

  <metahttp-equiv="expires"content="0">   

  <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

  <metahttp-equiv="description"content="This is my page">

  <!--

  <link rel="stylesheet" type="text/css" href="styles.css">

  -->

 

 </head>

 

 <body>

   <formaction="person/save.do"method="post">

       <tablewidth="80%"align="center">

         <tr>

            <td><label>姓名:</label><inputtype="text"name="name"></td>

            <td><label>性别:</label>

               <selectname="gender">

                  <optionvalue="">请选择</option>

                  <optionvalue="0" ></option>

                  <optionvalue="1" ></option>

               </select>

            </td>

            <td><label>地址:</label><inputtype="text"name="personAddr"></td>

            <td><label>生日:</label><inputtype="text"name="birthday"></td>

            <td><inputtype="submit"value="保存"></td>

         </tr>

      </table>

   </form>

 </body>

</html>

13 list.jsp

<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@tagliburi="http://java.sun.com/jsp/jstl/fmt" prefix="f"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <basehref="<%=basePath%>">

   

   <title>My JSP ‘list.jsp‘ starting page</title>

   

  <metahttp-equiv="pragma"content="no-cache">

  <metahttp-equiv="cache-control"content="no-cache">

  <metahttp-equiv="expires"content="0">   

  <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

  <metahttp-equiv="description"content="This is my page">

  <!--

  <link rel="stylesheet" type="text/css" href="styles.css">

  -->

  <scripttype="text/javascript">

     function delPerson(personId){

        if(confirm("真删吗?")){

           window.location.href=http://www.mamicode.com/"person/delete.do?personId="+personId;

        }

     }

  </script>

 </head>

 

 <body>

   <formaction="person/listPerson.do"method="post">

       <tablewidth="80%"align="center">

         <tr>

            <td><label>姓名:</label><inputtype="text"name="name"value="${name }"></td>

            <td><label>性别:</label>

               <selectname="gender">

                  <optionvalue="">请选择</option>

                  <optionvalue="0"<c:if test="${gender == ‘0‘ }">selected</c:if>></option>

                  <optionvalue="1"<c:if test="${gender == ‘1‘ }">selected</c:if>></option>

               </select>

            </td>

            <td><label>地址:</label><inputtype="text"name="personAddr"value="${personAddr }"></td>

            <td><label>生日:</label><inputtype="text"name="birthday"value="<f:formatDatevalue="${birthday }"pattern="yyyy-MM-dd"/>"></td>

            <td><inputtype="submit"value="查询"></td>

         </tr>

      </table>

   </form>

   <tablealign="center"width="80%">

      <tr>

         <td><ahref="person/toSave.do">添加</a></td>

      </tr>

   </table>

  

  <tablewidth="80%"align="center"border="1">

      <tr>

         <th>姓名</th>

         <th>性别</th>

         <th>地址</th>

         <th>生日</th>

         <th>操作</th>

      </tr>

      <c:forEachitems="${pList }"var="person">

         <tr>

            <td>${person.name }</td>

            <td>

               <c:iftest="${person.gender == ‘0‘ }"></c:if>

               <c:iftest="${person.gender == ‘1‘ }"></c:if>

           </td>

            <td>${person.personAddr }</td>

            <td><f:formatDatevalue="${person.birthday }"pattern="yyyy-MM-dd"/></td>

            <td><ahref="person/getPerson.do?personId=${person.personId }">修改</a>

           

            <ahref="javascript:void(0)"onclick="delPerson(${person.personId})">删除</a></td>

         </tr>

      </c:forEach>

     

  </table>

 </body>

</html>

14 update.jsp

<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@tagliburi="http://java.sun.com/jsp/jstl/fmt" prefix="f"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <basehref="<%=basePath%>">

   

   <title>My JSP ‘list.jsp‘ starting page</title>

   

  <metahttp-equiv="pragma"content="no-cache">

  <metahttp-equiv="cache-control"content="no-cache">

  <metahttp-equiv="expires"content="0">   

  <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

  <metahttp-equiv="description"content="This is my page">

  <!--

  <link rel="stylesheet" type="text/css" href="styles.css">

  -->

 

 </head>

 

 <body>

   <formaction="person/update.do"method="post">

   <inputtype="hidden"name="personId"value="${person.personId }">

       <tablewidth="80%"align="center">

        

         <tr>

            <td><label>姓名:</label><inputtype="text"name="name"value="${person.name }"></td>

            <td><label>性别:</label>

               <selectname="gender">

                  <optionvalue="">请选择</option>

                  <optionvalue="0"<c:if test="${person.gender == ‘0‘ }">selected</c:if>></option>

                  <optionvalue="1"<c:if test="${person.gender == ‘1‘ }">selected</c:if>></option>

               </select>

            </td>

            <td><label>地址:</label><inputtype="text"name="personAddr"value="${person.personAddr }"></td>

            <td><label>生日:</label><inputtype="text"name="birthday"value="<f:formatDatevalue="${person.birthday }"pattern="yyyy-MM-dd"/>"></td>

            <td><inputtype="submit"value="修改"></td>

         </tr>

      </table>

   </form>

 

     

 </body>

</html>

 

 

 

 

 

 

06_MyBatis,Spring,SpringMVC整合