Mybatis基础二+SSM基本配置


mybatis别名(掌握)


		<typeAliases>
            <!-- a)内置别名
                    常用基本类型 和包装类型 8 个 以及集合类型
            -->
           <!-- b)自定义别名(1)单独配置类的实现
            <typeAlias type="cn.itsource.mybatis.query.ProductQuery" alias="productQuery"></typeAlias>
            <typeAlias type="cn.itsource.mybatis.domain.Product" alias="product"></typeAlias>-->
           <!-- (2)配置包形式 推荐-->
            <package name="cn.itsource.mybatis.query"></package>
            <package name="cn.itsource.mybatis.domain"></package>
        </typeAliases>

映射器Mapper(练习掌握)


步骤:

​ (1) 创建项目 配置mybatis-config.xml 和昨天一样

​ (2) 创建接口 ProductMapper (XXXXMapper) 里面定义一个方法findAll -->以前dao层/mapper层

(3) 在对应的ProductMapper.xml namespace 和

​ 标签里面id (namespace+id) == (ProductMapper包路径+方法)

<?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="cn.itsource._01_mapper.mapper.ProductMapper">
    <select id="findAll"  resultType="product">
        select * from product
    </select>  
</mapper>

(4) 测试类 测试Mapper

   @Test
    public void testMapper(){
        //得到mapper --映射器 (动态代理)
        ProductMapper productMapper = MybatisUtil.INSTANCE.getSqlSession().
                getMapper(ProductMapper.class);

        for (Product product : productMapper.findAll()) {
            System.out.println(product);
        }

    }

高级查询注意事项


  (1)错误写法:
  <if test="productName != null">
                and productName like '%#{productName}%'
  </if>
    正确写法: --存在sql注入问题
     <if test="productName != null">
                and productName like '%${productName}%'
     </if>
   正确写法:
  	  <if test="productName != null">
                and productName like concat('%',#{productName},'%')
      </if>
      
   (2)特殊符号转义:
   <!-- salePrice minPrice 和maxPrice之间 特殊符号需要转义-->
           <!-- <if test="minPrice != null and  maxPrice != null">
                and salePrice > #{minPrice} and salePrice &lt; #{maxPrice}
            </if>-->
            <if test="minPrice != null and  maxPrice != null">
                <![CDATA[
                  and salePrice > #{minPrice} and salePrice <= #{maxPrice}
                ]]>
    		</if>

结果映射


​ 处理数据库里面的列 和 对象里面的字段 不一统一的情况下

(1)使用别名就可以解决
 <select id="findAll"  resultType="product">
            select id,productName pName,salePrice,costPrice,cutoff from product
 </select>
(2)返回Map解决映射问题 
 
 <select id="findAll"  resultMap="productMap">
        select id,productName,salePrice,costPrice,cutoff from product
    </select>
    <resultMap id="productMap" type="product">
        <!-- id:主键
            property:类里面的属性
            column:查询列名称
          -->
        <id property="id" column="id"></id>
        <result property="pName" column="productName"></result>
        <result property="salePrice" column="salePrice"></result>
    </resultMap>

关系处理


5.1 关系

​一对一 : 一个身份证对 一个人 一夫一妻 qq 和qq空间

一对多: 一个老师 对应多个学生 / 产品分类 对应多个产品 / 1个部门对应多个员工

多对一: 和一对多 相反

多对多: 多个老师 对应多个学生 (一对多或者多对一组合情况)

​ 用户 和 角色

​ 角色和权限

mybatis怎么处理关系:

​ 一对一 :mybatis处理一方

​ 多对一:mybatis处理一方

​ 多对多: mybatis处理多方

​ 一对多:mybatis处理多方

5.2 对一方处理(多对一/一对一)

嵌套结果: 只发送一条sql

嵌套查询: 发送 1+n条sql

<?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="cn.itsource._03_manytoone.mapper.ProductMapper">

   <!-- <resultMap id="productMap" type="product">
        <id column="id" property="id"></id>
        <result column="productName" property="pName"></result>
        <result column="salePrice" property="salePrice"></result>
        <result column="costPrice" property="costPrice"></result>
        <result column="cutoff" property="cutoff"></result>
        &lt;!&ndash; 处理一方&ndash;&gt;
        <association property="dir" javaType="productDir">
            <id column="did" property="id"></id>
            <result column="dname" property="dirName"></result>
        </association>

    </resultMap>-->
    <!-- (1)嵌套结果 发送一条sql语句-->
   <!-- <select id="findAll"  resultMap="productMap">
       SELECT
            p.id,
            p.productName,
            p.salePrice,
            p.costPrice,
            p.cutoff,
            dir.id did,
            dir.dirName  dname
        FROM
            product p
        JOIN productDir dir ON p.dir_id = dir.id
    </select>-->
    <!-- 嵌套查询:发送多sql语句(1+n条sql)-->

    <select id="findAll"  resultMap="productMap">
        SELECT
        p.id,p.productName,p.salePrice, p.costPrice,p.cutoff,p.dir_id
        FROM product p
    </select>
    <resultMap id="productMap" type="product">
        <id column="id" property="id"></id>
        <result column="productName" property="pName"></result>
        <result column="salePrice" property="salePrice"></result>
        <result column="costPrice" property="costPrice"></result>
        <result column="cutoff" property="cutoff"></result>
        <!--根据上面查询dir_id 在去查询 分类对象-->
        <association property="dir" column="dir_id" javaType="productDir" select="selectDir">
        </association>

    </resultMap>
    <select id="selectDir" parameterType="long" resultType="ProductDir">
        select * from productDir where id = #{dir_id}
    </select>




</mapper>

5.3 对多方进行处理(一对多/多对多)

嵌套结果和前台查询

<?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="cn.itsource._04_onetomany.mapper.ProductDirMapper">

    <!-- 嵌套结果-->
   <!-- <select id="findAll" resultMap="productDirMap">
        select dir.id ,dir.dirName,
                p.id pid,p.productName pName,p.salePrice,p.costPrice,p.cutoff
        from productDir dir join product p
        on dir.id = p.dir_id
    </select>
    <resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" ofType="product">
            <id property="id" column="pid"></id>
            <result property="pName" column="pName"></result>
            <result property="salePrice" column="salePrice"></result>
            <result property="costPrice" column="costPrice"></result>
        </collection>
    </resultMap>-->
    <!-- 嵌套查询-->
    <select id="findAll" resultMap="productDirMap">
        select dir.id ,dir.dirName from productDir dir
    </select>

    <resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" column="id" ofType="product" select="selectProducts">
        </collection>

    </resultMap>
    <select id="selectProducts" parameterType="long" resultType="product">
        select id,productName pName,salePrice,costPrice,cutoff
         from product where dir_id = #{dir_id}
    </select>



</mapper>

5.4 延迟加载–了解

​ 使用的时候,才去加载内容

​ product.jsp -->展示所有的产品 把产品的分类展示

​ 以后常用项目模式都是前台端分离模式

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v7ShNiu6-1577354826593)(笔记.assets/image-20191226141539943.png)]

5.5 缓存-了解

mybatis 支持缓存 (一级缓存 和二级缓存)

redis(nosql的数据库 做缓存)

5.5.1 mybatis一级缓存

属于sqlSession级别缓存(entityManager类似)

命中条件:

​ mybatis一级缓存 命中(同一个SqlSessionFactory 同一个SqlSession 同一个ID)

 public void testMapper(){
        //得到mapper --映射器 (动态代理)

        SqlSession sqlSession1 =  MybatisUtil.INSTANCE.getSqlSession();
        //mybatis一级缓存 命中(同一个SqlSessionFactory 同一个SqlSession 同一个ID)
        ProductMapper mapper1 = sqlSession1.getMapper(ProductMapper.class);
        System.out.println(mapper1.findOne(19L));

        ProductMapper mapper2 = sqlSession1.getMapper(ProductMapper.class);
        System.out.println(mapper2.findOne(19L));

    }

5.5.2 mybatis二级缓存

命中条件: 同一个SqlSessionFactory 不同的SqlSession 同一个ID

    SqlSession sqlSession1 =  MybatisUtil.INSTANCE.getSqlSession();
    //mybatis一级缓存 命中(同一个SqlSessionFactory 同一个SqlSession 同一个ID)
    ProductMapper mapper1 = sqlSession1.getMapper(ProductMapper.class);
    System.out.println(mapper1.findOne(19L));

    ProductMapper mapper2 = sqlSession1.getMapper(ProductMapper.class);
    System.out.println(mapper2.findOne(19L));

​ 什么叫序列化: 把对象转换成二进制的信息 这个过程

​ 为什么需要序列化: 用在网络传输

反序列化:把二进制内容转成对象的形式 这个过程

SSM基础(掌握)


配置文件

applicationContext.xml --配置spring+mybatis
<?xml version="1.0" encoding="UTF-8"?>


<context:component-scan base-package=“cn.itsource.ssm.service”></context:component-scan>

<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:db.properties" />
<!--创建dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!--sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml"></property>
    <property name="typeAliasesPackage">
        <value>
            cn.itsource.ssm.domain
        </value>
    </property>
</bean>
<!-- mapper spring -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.itsource.ssm.mapper"></property>
</bean>

<!--事务配置-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解的支持,默认会去找一个名称叫做transactionManager的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />
applicationCotnext-mvc.xml --配置springmvc
<?xml version="1.0" encoding="UTF-8" ?>

<!--扫描controller-->
<context:component-scan base-package="cn.itsource.ssm.web.controller" />
<!--静态资源处理-->
<mvc:default-servlet-handler />
<!--识别@RequestMapping等注解支持-->
<mvc:annotation-driven />
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>
db.properties --配置库

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///
jdbc.username=
jdbc.password=

web.xml --配置web的内容
<?xml version="1.0" encoding="UTF-8"?>

<!--
    监听器

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

<!--核心控制器-->
<servlet>
    <servlet-name>dispatchServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatchServlet</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>
log4j.properties

log4j.rootLogger=ERROR, stdout

#log4j.rootLogger=NONE 不想打印日志信息
#log4j.rootLogger=NONE
#日志等级:OFF level>FATAL>ERROR>WARN>INFO>DEBUG>tarce>ALL level

#扫描包 配置自己的包
#TRACE 堆栈信息
log4j.logger.cn.itsource=TRACE

#ConsoleAppender 输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#layout:格式样式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#采用下面的样式输出
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

扩展

字段别名

</resultMap>

***

## 一对多分页

***

```xml



<select id="findAll" resultMap="productDirMap">
        select dir.id ,dir.dirName,
                p.id pid,p.productName pName,p.salePrice,p.costPrice,p.cutoff
        from productDir dir join product p
        on dir.id = p.dir_id
        limit 0,2
    </select>
    <resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" ofType="product">
            <id property="id" column="pid"></id>
            <result property="pName" column="pName"></result>
            <result property="salePrice" column="salePrice"></result>
            <result property="costPrice" column="costPrice"></result>
        </collection>
    </resultMap>

建议使用嵌套查询:

<select id="findAll" resultMap="productDirMap">
        select dir.id ,dir.dirName from productDir dir limit 0,2
    </select>

    <resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" column="id" ofType="product" select="selectProducts">
        </collection>

    </resultMap>
    <select id="selectProducts" parameterType="long" resultType="product">
        select id,productName pName,salePrice,costPrice,cutoff
         from product where dir_id = #{dir_id}
    </select>

常见错误

*11.1********写的mapper文件没有在配置文件里面注册*

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for cn.itsource.mybatis.crud.UserMapper.createTable

配置找不到方法

*11.2********返回的结果是List,而需要的是一个对象*

org.apache.ibatis.executor.ExecutorException: Statement returned more than one row, where no more than one was expected.

Product findAll()

<select id="findAll" 
   resultType="cn.itsource.mybatis.c_manytoone.Dept"		parameterType="long">		
select id,name from t_dept where id=#{id}	
</select>

11.3 *没有序列化异常*

使用缓存,如果报序列化问题,让类去实现序列化接口

implements Serializable

什么是序列化–面试题

​ 把java对象转换二进制过程

什么情况下使用序列化

1、在网络中直接传输一个java对象。

2、在数据库的Blob(二进制)字段(列)中,直接存一个java对象会出问题

3、当前,需要把java对象放入内存(本地的临时文件)中

java.io.ObjectInputStream

java.io.ObjectOutputStream

4.HttpSession里面存放对象,tomcat的内存不足(500M)的时候,钝化到硬盘

springmvc是一种基于Spring框架的MVC(Model View Controller)开发模式的Web开发框架。它能够帮助开发者更好地管理请求和响应,让开发过程更加简洁和灵活。MyBatis是一个优秀的持久层框架,可以与Spring相结合进行数据库操作。它能够通过注解或XML配置文件实现数据库的增删改查操作,使开发者能够高效地操作数据库。电商项目是一种在线购物平台,用户可以浏览商品信息、下单购买、查看订单等。Java商城源码是这种电商项目的实现代码,通过使用SpringMVC和MyBatis,能够快速搭建一个完整的电商网站。 SSM框架是指Spring+SpringMVC+MyBatis的组合,是一种常用的JavaWeb开发框架。Spring是一个轻量级的开源框架,提供了很多实用的功能,包括IOC(控制反转)和AOP(面向切面编程)等。SpringMVC是基于Spring的MVC框架,可以实现请求的分发和处理。MyBatis是一个持久层框架,可以与SpringMVC结合使用,完成数据库的操作。Maven是一种软件项目管理工具,可以自动下载和配置项目所需的第三方库和工具。 对于这个电商项目的Java商城源码,使用SSM框架和Maven进行开发是一个不错的选择。首先,可以使用Maven来管理项目所需的依赖库,避免手动下载和配置的繁琐过程。其次,使用Spring来提供IOC容器和AOP功能,可以简化开发过程,并且使代码更加易于维护。然后,使用SpringMVC来处理请求和响应,实现网站的跳转和业务逻辑的处理。最后,使用MyBatis来完成与数据库的交互,实现商品信息的增删改查等功能。 综上所述,使用SSM框架和Maven进行开发的电商项目Java商城源码,能够快速搭建一个完整的电商网站,实现商品的展示、购买和订单的管理等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值