zoukankan      html  css  js  c++  java
  • Springmvc+spring+mybatis整合

    整合的配置文件:

    spring (applicationContext.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/tool"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd">
    
    
    
    <!-- 配置数据源   -->
            <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--                <property name="driverClass" value="com.mysql.jdbc.Driver" />-->
    <!--                <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test1?useUnicode=true&amp;characterEncoding=UTF-8" />-->
    <!--                <property name="user" value="root" />-->
    <!--                <property name="password" value="root" />-->
    
                    <!--连接Orcal-->
                    <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
                    <property name="jdbcUrl" value="jdbc:oracle:thin:localhost:1521:orcl"/>
                    <property name="user" value="ssm"/>
                    <property name="password" value="root"/>
            </bean>
    
    
    
    
            <!--  。。。。。。。。。。。。。。。。。。。。  持久层。。。。。。。。。。。。。。。。。。。。    -->
    
           <!--    整合Mybatis配置    -->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                    <property name="dataSource" ref="datasource"></property>
                    <!--    加载mybatis的配置文件            -->
                    <property name="configLocation" value="classpath:mybatis.xml"></property>
    
                    <!--    加载mybatis的Mapping文件            -->
                    <property name="mapperLocations" value="classpath*:com/cn/entity/mybatisUserMapper.xml"></property>
    
                    <!--    加载指定包 并且直接指定类名为 简单的名字            -->
                    <property name="typeAliasesPackage" value="com.cn.entity"></property>
    
            </bean>
    
            <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
                    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
            </bean>
    
    
    
    
    
            <!--  。。。。。。。。。。。。。。。。。。。。  事务与Aop配置。。。。。。。。。。。。。。。。。。。。    -->
            <!--  配置事务管理器      -->
            <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                    <property name="dataSource" ref="datasource"></property>
            </bean>
            <tx:advice id="advice" transaction-manager="txManager">
                    <tx:attributes>
                            <!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 -->
                            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" /> <!--需要走事务所以需要配置隔离级别 pro..-->
                            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
                            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception" />
                            <tx:method name="find*"  read-only="true" />
                    </tx:attributes>
            </tx:advice>
            <aop:config>
                    <aop:pointcut id="pointcut" expression="execution(* com.cn.service.impl.*.*(..))"/>
                    <aop:advisor advice-ref="advice" pointcut-ref="pointcut"></aop:advisor>
            </aop:config>
    
    
    
            <!--  。。。。。。。。。。。。。。。。。。。。  配置自动扫描。。。。。。。。。。。。。。。。。。。。    -->
            <!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。 -->
            <context:component-scan base-package="com.cn">
                    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
            </context:component-scan>
    
    
    
    
    
    
    
    
            <!--    如果使用注解实现aop 和事务的话就需要开启对应的 注解扫描器    -->
    <!--        <aop:aspectj-autoproxy/> -->
    <!--        <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>-->
    
    
    
    
    
    
            <!-- 配置 转换器,对于在basePackage设置的包(包括子包)下的接口类,
                    如果接口类的全类名在Mapper.xml文件中和定义过命名空间一致,
                    将被转换成spring的BEAN,在调用
                    的地方通过@Autowired方式将可以注入接口实例      意思是只需要写接口不需要去写实现类-->
    
    <!--        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
    <!--                <property name="sqlSessionFactory" ref="sqlSessionFactory" />-->
    <!--                <property name="basePackage" value="com.gsj.dao" />-->
    <!--        </bean>-->
    
    
    </beans>

    mybatis配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
    
        <!-- 加载Src下的配置文件   -->
    <!--    <properties resource="db.properties"/>-->
        <!--别名机制-->
    <!--    <typeAliases>-->
    <!--        <typeAlias type="com.cn.entity.User" alias="user"/>-->
    <!--        <typeAlias type="com.cn.entity.Student" alias="student"></typeAlias>-->
    <!--    </typeAliases>-->
    
        <!-- 连接数据库   -->
    <!--    <environments default="mysql_development">-->
    
    <!--        <environment id="mysql_development">-->
    <!--            <transactionManager type="JDBC"/>-->
    <!--            <dataSource type="POOLED">-->
    <!--                <property name="driver" value="${driverClass}"/>-->
    <!--                <property name="url" value="${jdbcUrl}"/>-->
    <!--                <property name="username" value="xxx"/>-->
    <!--                <property name="password" value="xxx"/>-->
    <!--            </dataSource>-->
    <!--        </environment>-->
    
            <!--  连接Oracle数据库  -->
    <!--        <environment id="oracle_development">-->
    <!--            <transactionManager type="JDBC"/>-->
    <!--            <dataSource type="POOLED">-->
    <!--                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>-->
    <!--                <property name="url" value="jdbc:oracle:thin:localhost:1521:orcl"/>-->
    <!--                <property name="username" value="ssm"/>-->
    <!--                <property name="password" value="${password}"/>-->
    <!--            </dataSource>-->
    <!--        </environment>-->
    <!--    </environments>-->
    
    
    
        <!-- 加载映射文件   -->
    <!--    <mappers>-->
    <!--        <mapper resource="com/cn/entity/mybatisUserMapper.xml"/>-->
    <!--        <mapper resource="com/cn/entity/mybatisUserMapper2.xml"/>-->
    <!--        <mapper resource="com/cn/entity/studentMapper.xml"/>-->
    
    <!--        <mapper resource="com/cn/entity2/cardMapper.xml"/>-->
    <!--        <mapper resource="com/cn/entity2/studentMapper1.xml"/>-->
    
    
    <!--        <mapper resource="com/cn/entity3/gradMapper.xml"/>-->
    <!--        <mapper resource="com/cn/entity3/studentsMapper.xml"/>-->
    <!--    </mappers>-->
    <!--    -->
    </configuration>

    Beanmapper文件配置

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    
    <mapper namespace="com.cn.entity.User" >
    
        <!--一个resultmap相当与一张数据表与实体的设 当实体与数据库表字段不一直时需要配置-->
        <resultMap id="usermap" type="user">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="sex" column="sex"></result>
            <result property="address" column="address"></result>
        </resultMap>
    
        <select id="findAll" resultMap="usermap">
            select * from userInfor     sql语句千万不能写分号;不然汇报 “无效字符错误”
        </select>
    </mapper>

    Controller层

    package com.cn.controller;
    
    import com.cn.dao.UserDao;
    import com.cn.entity.User;
    import com.cn.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.List;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
    
        @Autowired
        private UserService userServiceImpl;
    
        @RequestMapping("/findAll")
        public @ResponseBody List<User> findAll(Model model, HttpServletRequest request) throws Exception{
            System.out.println("hello ...我是spring和mybatis整合");
            return userServiceImpl.findAll();
        }
    
    }

    Service层

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDaoImpl;
    
        @Override
        public List<User> findAll() {
            return userDaoImpl.findAll();
        }
    }

    Dao层

    package com.cn.dao;

    import com.cn.entity.User;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;

    import java.util.List;

    @Repository
    public class UserDaoImpl implements UserDao {


    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public List<User> findAll() {
    System.out.println(sqlSessionTemplate);
    List<User> users = sqlSessionTemplate.selectList("com.cn.entity.User.findAll");
    return users;
    }
    }

    jsp层

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
        <script type="text/javascript" src="jquery-3.3.1.js"></script>
    
      </head>
      <body>
        <input id="fangwen" type="button" value="访问"/>
      </body>
    </html>
    
    
    <script type="text/javascript">
              $(function () {
                 $("#fangwen").click(function () {
                     $.post("${pageContext.request.contextPath}/user/findAll.action",{},function (data,status,ajax) {
                       alert(ajax.responseText);
                     });
                 });
    
              });
    </script>

    返回Json数据的格式:
    [{"id":"1","username":"spring_mvc","sex":"男","address":"意大利"},{"id":"2","username":"mybatis_mvc","sex":"女","address":"俄罗斯"}]
    坚持
  • 相关阅读:
    Linux学习65 实战使用awk高级功能统计网络请求连接状态
    Linux学习64 awk使用与实战
    Linux学习63 shell脚本高级编程-信号捕捉实战
    Linux学习62 shell脚本高级编程-数组和字符串处理
    Linux学习61 企业军工级别安全策略-SELinux简介
    Linux学习60 centos7新特性-systemd及systemctl实战
    Linux学习59 shell脚本高级用法-函数编程与应用实战
    【HBase】HBase与MapReduce的集成案例
    【HBase】底层原理
    【HBase】Java实现过滤器查询
  • 原文地址:https://www.cnblogs.com/gaoSJ/p/13053961.html
Copyright © 2011-2022 走看看