Mybatis(四)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: Mybatis相关介绍

⑧.SSM整合

applicationContext.xml
    1.组件扫描service
    2.加载数据库配置文件
    3.配置数据源
    4.配置SqlSessionFactory,依赖数据源[mybatis+spring整合]
      JdbcTemplate,依赖数据源
    5.配置ScannerMapperConfigurer,加载mybatis的核心文件
    6.配置事务
web.xml
    1.Spring监听器,加载spring配置文件
    2.配置过滤器,解决乱码问题
    3.配置前端控制器
    4.系统默认页面  
spring-mvc.xml
  1.组件扫描controller
  2.配置注解驱动
  3.配置内部资源视图扫描器
  4.开放静态资源访问权限

20191008165718542.png

20191008153110523.png


  • ①. log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
  • ②. jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
  • ③. 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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
     <!--组件扫描 扫描service和mapper-->
     <context:component-scan base-package="com.itheima.service">
        <!--排除controller的扫描-->
        <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>-->
     </context:component-scan>
     <!--加载配置文件-->
     <context:property-placeholder location="classpath:jdbc.properties"/>
     <!--配置数据源-->
     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
     <property name="driverClassName" value="${jdbc.driver}"/>
     <property name="url" value="${jdbc.url}"/>
     <property name="username" value="${jdbc.username}"/>
     <property name="password" value="${jdbc.password}"/>
     </bean>
     <!--配置事务-->
         <!--1.配置事务管理器-->
         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"></property>
         </bean>
         <!--2.配置通知-->
         <tx:advice id="txAdvice" transaction-manager="transactionManager">
             <tx:attributes>
                 <tx:method name="*" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"></tx:method>
             </tx:attributes>
         </tx:advice>
         <!--3.织入:将通知和切入点相结合-->
        <aop:config>
             <aop:pointcut id="pointCutId" expression="execution(* com.itheima.service.*.*(..))"/>
             <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCutId"></aop:advisor>
        </aop:config>
     <!--配置MyBatis的SqlSessionFactory-->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <!--底层需要connection,需要注入dataSource-->
         <property name="dataSource" ref="dataSource"/>
         <!--加载mybatis核心文件-->
         <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
     </bean>
    <!--扫描Mapper所在包,为mapper创建实现类
    所以在service中只需要注入即可!
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.mapper"></property>
    </bean>
</beans>
  • ④. spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
                        http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--组件扫描 主要扫描controller-->
    <context:component-scan base-package="com.itheima.controller"/>
    <!--配置注解驱动-->
    <mvc:annotation-driven/>
    <!--内部资源视图扫描器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--开放静态资源访问权限-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>
  • ⑤.sqlMapConfig.xml
<?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>
    <!--自定义别名-->
    <typeAliases>
        <typeAlias type="com.itheima.domain.Account" alias="account"></typeAlias>
    </typeAliases>
</configuration>
  • ⑥.web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <!--Spring监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--SpringMvc的前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  • ⑦.mapper
  <?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="userMapper">    
    <select id="findAll" resultType="com.itheima.domain.User">        
      select * from User    
    </select>
  </mapper>
  • ⑧.jar包
<dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <!--servlet和jsp-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!--mybatis相关-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>c3p0</groupId>-->
        <!--<artifactId>c3p0</artifactId>-->
        <!--<version>0.9.1.2</version>-->
        <!--</dependency>-->
        <!--测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

2.mybatis项目中学习

1>. 如何获取自增产生的id?selectKey

    <insert id="add" parameterType="com.itheima.pojo.CheckGroup">
        /*
        通过mybatis框架提供的selectKey来获得自增产生的id值
        order:insert 与 selectKey的执行顺序(BEFORE|AFTER)
        keyProperty:这个属性不能乱写,要对应CheckGroup实体类中的id
        */
       <selectKey resultType="int" order="AFTER" keyProperty="id">
           select LAST_INSERT_ID()
       </selectKey>
        insert into t_checkgroup(code,name,helpCode,sex,remark,attention)
        values
        (#{code},#{name},#{helpCode},#{sex},#{remark},#{attention})
    </insert>

2>. 级联查询

  • 需求:通过用户的username查询出对应的角色和权限

20191029093022566.png

User:
    private Integer id; // 主键
    private Date birthday; // 生日
    private String gender; // 性别
    private String username; // 用户名,唯一
    private String password; // 密码
    private String remark; // 备注
    private String station; // 状态
    private String telephone; // 联系电话
    private Set<Role> roles = new HashSet<Role>(0);//对应角色集合
    userDao.xml
    <resultMap id="baseMap" type="com.itheima.pojo.User">
        <id column="id" property="id"></id>
        <result column="birthday" property="birthday"></result>
        <result column="gender" property="gender"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="remark" property="remark"></result>
        <result column="station" property="station"></result>
        <result column="telephone" property="telephone"></result>
    </resultMap>
    <resultMap id="UserMap" type="com.itheima.pojo.User" extends="baseMap">
       <!-- private Set<Role> roles = new HashSet<Role>(0);//对应角色集合-->
       <collection
               property="roles"
               ofType="com.itheima.pojo.Role"
               这里的id是select * from t_user...查询出来的结果的id
               column="id"         
               select="com.itheima.dao.RoleDao.findUserIdByRoles">
       </collection>
    </resultMap>
    <select id="findByUsername2" parameterType="string" resultMap="UserMap">
        select * from t_user where username=#{username}
    </select>
public class Role implements Serializable {
    private Integer id;
    private String name; // 角色名称
    private String keyword; // 角色关键字,用于权限控制
    private String description; // 描述
    private Set<User> users = new HashSet<User>(0);
    private Set<Permission> permissions = new HashSet<Permission>(0);
    }
RoleDao.xml
    <resultMap id="baseMap" type="com.itheima.pojo.Role">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="keyword" property="keyword"></result>
        <result column="description" property="description"></result>
    </resultMap>
    <resultMap id="RolesMap" type="com.itheima.pojo.Role" extends="baseMap">
        <collection property="permissions"
                    column="id"
                    ofType="com.itheima.pojo.Permission"
                    select="com.itheima.dao.PermissionDao.findRoleIdsByPserssion">
        </collection>
    <select id="findUserIdByRoles" resultMap="RolesMap" parameterType="int">
        select * from t_role where id in(select role_id from t_user_role
         where user_id=#{user_id})
    </select>
perssionDao.xml
    <select id="findRoleIdsByPserssion" resultType="com.itheima.pojo.Permission" 
    parameterType="int">
    select * from t_permission where id in(select permission_id
     from t_role_permission where role_id=#{role_id})
    </select>


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
SQL Java 数据库连接
|
XML Java 数据库连接
|
SQL XML Java
|
1月前
|
SQL 缓存 Java
Mybatis汇总
Mybatis汇总
29 1
|
Java 数据库连接 测试技术
Mybatis-PLUS详解
Mybatis-PLUS详解
244 0
|
SQL Java 关系型数据库
mybatis plus很好,但是我被它坑了!
作者今天在开发一个后台发送消息的功能时,由于需要给多个用户发送消息,于是使用了 mybatis plus 提供的 saveBatch() 方法,在测试环境测试通过上预发布后,测试反应发送消息接口很慢得等 5、6 秒,于是我就登录预发布环境查看执行日志,发现是 mybatis plus 提供的 saveBatch() 方法执行很慢导致,于是也就有了本篇文章。
71 1
|
Java 数据库连接 测试技术
mybatis中@Many
mybatis中@Many
111 0
|
SQL Java 数据库连接
|
SQL XML 存储
Mybatis总结
Mybatis总结
110 0
|
SQL Java 数据库连接