mybatis_day01

Mybatis01

1.什么是mybatis

1.1mybatis

一个基于Java的持久层框架

1.2持久层

操作数据库那层代码

项目分层:

界面层(jps/controller) 业务层(service) 持久层(数据层 dao)

持久层框架:jdbc jpa springjdbc springdatajps mybatis

1.3框架

1. 每个框架都是为了解决某一领域的问题而产生的。

2. 框架都是一个半成品,已经完成衣服分功能,只需要再上面进行开发----提高了开发效率

3. 可以让我们很多人写的代码都按照一定规则去写--可读性 维护性(orm规范)

1.4持久化概念

把内存里面的数据保存到数据库中--这个过程就叫做持久化

1.5mybatis它是一个持久层框架,同时有个ORM的框架

ORM:对象映射关系---jpa/springdatajpa

2.mybatis的特点

2.1mybatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架

2.2mybatis消除了几乎所有的JDBC代码和手工设置参数以及结果集的检索

2.3mybatis使用简单的xml或注解 用于配置和原始映射,将接口和Javapojos(普通的java对象)映射成数据库中的记录。

3.使用Mybatis

3.1创建项目并导入jar

 

3.2写配置文件

Mybatis-config.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>

    <!-- 开发环境-->

    <environments default="development">

        <!--

            一个环境  id:为这个环境取唯一一个id名称

        -->

        <environment id="development">

            <!--

                事务管理   type:JDBC(支持事务)/MANAGED(什么都不做)

                 mysql: innodb  MyISAM

            -->

            <transactionManager type="JDBC" />

            <!-- 数据源, 连接池  type(POOLED):MyBatis自带的连接池 -->

            <dataSource type="POOLED">

                <!-- 连接数据库的参数 四大金刚  -->

                <property name="driver" value="com.mysql.jdbc.Driver" />

                <property name="url" value="jdbc:mysql:///mybatis" />

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

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

            </dataSource>

        </environment>

    </environments>

    <!-- 这个mappers代表的是相应的ORM映射文件 -->

    <mappers>

        <mapper resource="cn/itsource/mybatis/domain/ProductMapper.xml" />

    </mappers>

</configuration>

 

productMapper.xml

<?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:命名空间

      以后:通过namespace+id 调用对应的语句

-->

<mapper namespace="cn.itsource.mybatis.domain.ProductMapper">

    <!--

        select:表示查询标签

        id: 代表给标签取个名称 必须唯一

        resultType:返回值类型

    -->

    <select id="findAll" resultType="cn.itsource.mybatis.domain.Product">

          select * from product

     </select>

</mapper>

3.3测试。。

4.mybatiscrud

<?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:命名空间

      以后:通过namespace+id 调用对应的语句

-->

<mapper namespace="cn.itsource.mybatis.domain.ProductMapper">

    <!--

        select:表示查询标签

        id: 代表给标签取个名称 必须唯一

        resultType:返回值类型

    -->

    <select id="findAll" resultType="cn.itsource.mybatis.domain.Product">

          select * from product

     </select>

    <!--新增 parameterType 参数类型-->

    <insert id="save" parameterType="cn.itsource.mybatis.domain.Product">

        insert into product(productName,salePrice,costPrice,cutoff)

        values(#{productName},#{salePrice},#{costPrice},#{cutoff})

    </insert>

    <!--修改-->

    <update id="update" parameterType="cn.itsource.mybatis.domain.Product">

        update  product set  productName=#{productName},salePrice=#{salePrice}

        where id=#{id}

    </update>

    <!--删除 long Mybatis内置别名 long java.util.Long remove(13)-->

    <delete id="remove" parameterType="long">

        delete from product where id=#{id}

    </delete>

    <!--查询一条数据-->

    <select id="findOne" parameterType="long" resultType="cn.itsource.mybatis.domain.Product">

        select * from product where id=#{id}

    </select>

</mapper>

5.抽取工具类

enum方式

public enum  MybatisUtil {

 

    INSTANCE;

    private static SqlSessionFactory sqlSessionFactory;

    //静态代码块

    static{

        Reader reader = null;

        try {

            reader = Resources.getResourceAsReader("mybatis-config.xml");

            //SqlSessionFactory -->EntityManagerFactory

             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

        } catch (IOException e) {

            e.printStackTrace();

        }

   }

    //抽取一个 --sqlSession

    public SqlSession getSqlSession(){

        return  sqlSessionFactory.openSession();

    }

}

6.mybatis的一些细节

6.1获取主键

有时候 保存一条数据之后,需要拿到这条数据的主键,拿到之后可以做后续事情

场景:

角色的保存

useGeneratedKeys="true" keyColumn="id" keyProperty="id"

   <insert id="save" parameterType="cn.itsource.mybatis.domain.Product"

            useGeneratedKeys="true" keyColumn="id" keyProperty="id">

        insert into product(productName,salePrice,costPrice,cutoff)

        values(#{productName},#{salePrice},#{costPrice},#{cutoff})

</insert>

6.2日志

1. 为什么要使用日志

有时候,需要打印的sql的信息 比如sql的传参数 返回值 -- 必须使用日志

好处: 使用日志框架可以帮助我们进行分析与排错

2.  常用的日志框架

slf4j(抽象标准) -->很多实现 logging,logback,log4j

3. 使用日志框架log4j

(1) 导入jar

 

log4j.rootLogger=ERROR, stdout

 

日志等级(了解): OFF level > FATAL(致命) > ERROR(错误) > WARN (警告)>

#                INFO (提示)> DEBUG (调试)> trace > ALL level(所有配置)\

 

#输出效果 如果你设置日志级别是trace,则大于等于这个级别的日志都会输出

 

# 关闭日志输出

#log4j.rootLogger=NONE 不想打印日志 就配置NONE

# WARN为一般警告,比如session丢失、

# INFO为一般要显示的信息,比如登录登出、

# DEBUG为程序的调试信息

# TRACE 堆栈信息

# 扫描包 配置自己包

 

#注意点 包名/配置等级 配置DEBUG/ALL

log4j.logger.cn.itsource=DEBUG/TRACE

 

#ConsoleAppender:输出控制台

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

#layout: 格式样式

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

#采用下面的样式输出 [20191224]类名

log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

7.动态sql

高级查询

<sql id="whereSql">

        <where>

            <if test="productName != null">

                and productName = #{productName}

            </if>

            <if test="id != null">

                and id = #{id}

            </if>

        </where>

    </sql>

 

    <select id="queryByCondition" parameterType="cn.itsource.mybatis.query.ProductQuery"

            resultType="cn.itsource.mybatis.domain.Product">

          select * from product

          <include refid="whereSql"></include>

 

    </select>

posted @ 2019-12-25 21:27  dyier  阅读(124)  评论(0)    收藏  举报