Java框架ssm之MyBatis

MyBatis-概述

  1. MyBatis框架是一种可以替代原生态的JDBC,单纯的只使用JDBC话会使项目代码变得冗余,耦合度高,编写sql语句复杂,显得比较麻烦,开发人员为了避免这种问题和提高开发效率提供了相对应的框架支持—MyBatis
  2. MyBatis框架是一种持久层框架,支持自定义Sql语句、存储过程甚至是高级映射。MyBatis基本上避免了原生态的JDBC的复杂代码,包括一些设置Sql语句的参数、获取结果集的操作。MyBatis通过一些简单的XML文件或者一些封装好的注解来配置或者映射相对应的属性和原始映射类型、接口和JavaBean对象(ps:JavaBean对象封装好的普通Java类,也可以就叫做pojo(豆子)),将其作为数据库中的记录。
  3. 回顾JDBC的六个步骤:
    1.首先加载数据库的驱动
    2.获取数据库连接对象(Connection)
    3.获取Sql语句的对象(Statedment或者防止Sql注入现象的prepardstatement对象)
    4.执行Sql语句:根据作为执行Sql对象的方法参数,简单的分为两类:

执行select查询语句,接收对象为ResultSet类型

new PreparedStatement().executeQuery();

执行select查询语句,接收对象为ResultSet类型

new PreparedStatement().executeUpdate();

5.对查询结果集对象进行处理,如果不是查询语句的话就不需要进行这项步骤
6.释放资源

Mybatis的入门使用

1.获取并创建Sqsession会话对象

如果需要使用Mybatis技术的话,需要知道每一个Mybatis应用都是基于一个SqlSessionFactory的实例化对象为核心,基于该实例化对象之后进行调用build方法进行读取Mybatis核心的配置文件,这样使得核心配置文件(以及后续相关的Maper配置文件)和Java程序耦合在一起,同样利用xml配置文件使得某些固定数据直接固定在项xml文件中。每一个Mybatis应用中都需要进行获取的SqlSessionFactory对象可以封装在一个工具类中的。

public class MybatisUtil {
    public MybatisUtil() {
    }
    private static SqlSessionFactory  sqlSession = null;
    static {
        try {
            sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("Mybatis_config.xml"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建会话对象
    }
    public static SqlSession OpenSqlSession() {
        //获取会话开启对象
        return sqlSession.openSession();
    }

}

注意在一个Mybatis项目中获取会创建多个session会话事物对象,所以这个工具类会多次使用,但是读取该配置文件只需要进行一次(这里是为了解释为什么将实例化以及读取核心配置文件放在静态代码块中)避免了多次创建会话对象重复读取核心配置文件造成的冗余。

2.配置文件的初步应用

1.核心配置文件的应用,模板:

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    <properties resource="Properties.properties"/>-->
    <properties resource="Properties.properties">
        <property name="org.apache.ibatis.parsing.PropertyParser.enable-default-value" value="true"/>
        <property name="" value=""></property>
        <property name="" value=""></property>
        <property name="" value=""></property>
<!--        可以将配置文件中的属性配置在这里-->
    </properties>

<!--自从mybatis从3.4.2开始就开始进行需要手动配置启动外部Java资源的导入-->

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/studentmanager"/>
                <property name="username" value="root"/>
                <property name="password" value="7895123L"/>
            </dataSource>
        </environment>
        <environment id="DBZxr">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${DriverName}"/>
                <property name="url" value="${studentmanager}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
                <property name="poolMaximumActiveConnections" value="3"/>
                <property name="poolTimeToWait" value="5"/>
<!--                一定时间内只能有3个连接对象-->
            </dataSource>

        </environment>
<!--        在EL表达式中可以使用三目运算符,不过需要打开默认开关,即属性文件第一个-->
<!--        JNDI是为了能够集成Tomcat服务器的连接池对象-->
        <environment id="DBLab">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="" value=""/>
                <property name="" value=""/>
            </dataSource>
        </environment>
    </environments>

    <!--    指定Mapper路径资源-->
    <mappers>
        <mapper resource="User.xml"/>
    </mappers>

</configuration>

在该配置文件中有两种处理连接数据库所需要的用户名,密码,驱动位置,数据库名称,不同的资源处理方法或者配置位置可以使Mybatis操纵数据库变得更加灵活。因此可以根据自己的需求进行处理自己的配置方法,在原生态的jdbc中使用的方法是在根路径下创建一个properties文件,个人认为和Mybatis的效果是一样的,底层是一个Map集合一样。resource=“Properties.properties”,将自己配置的资源通过配置文件映射过来(可理解为传输出来)。当然也可以将配置文件资源直接放在这里

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

无非是使用的方法不同,在这里不过多概述
其次就是Mappeer配置文件的使用,在核心配置文件中的代码就是最后映射文件的名字

<mappers>
        <mapper resource="User.xml"/>
</mappers>

可以进行配置多个映射对象来对不同索引和视图的处理,因此创建多个Mapper表对处理数据库中的多张表的很有必要。
这里举一个Mapper例子,来对Mapper表中利用Mybatis进行CRUD的操作以及可能会出现的错误。

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="LoginMapper">
    <select id="selectMapper" resultType="Model.User">
        select *
        from user;
    </select>
    <select id="selectUsername">
        select *
        from user
        where username = #{username};
    </select>
    <select id="selectLevel">
        select level
        from user
        where username = #{level}
    </select>
    <select id="selectLogin" resultType="Model.User">
        select *
        from user
        where username = #{username}
          and password = #{password}
    </select>
    <insert id="insertRegister">
        insert into user(username, password, level)
        values (#{username}, #{password}, #{level});
    </insert>
    <select id="selectQueryuser" resultType="Model.User">
        select *
        from user
        order by username;
    </select>
    <insert id="InsertUser">
        insert into user
        values (#{username}, #{password}, #{level});
    </insert>
    <delete id="DeleteUser">
        delete
        from user
        where username = #{username};
    </delete>
    <update id="UpdateUser">
        update user
        set username=#{after_username},
            password=#{after_password},
            level   = #{after_level}
        where username = #{username};
    </update>
</mapper>

由于后续处理的表逐渐庞大,所以对xml表配置文件进行了命名,在Java程序中session对象进行操作读取配置文件注意命名的格式。
注意每一个具体配置操作都要有id
Insert操作
insert into 表名 (所要添加的字段名字) values(数据);
注意这里数据尽量需要设置成死的,因为在实际开发中所有的属性都是动态的,因此在后续Java程序中是可以传输一个Map集合或者一个JavaBean对象,让sql语句中的#{}字段自己进行通过映射获取数据。其中#{}该种方法可以避免sql注入现象。
Delete操作
delete from 表名 where 条件
Update操作
update set 字段=新的数据,字段=新的数据,where 条件
Select操作
select操作固定语句:select 字段名 from 表名 where 条件。注意在select语句中的属性信息,注意标注返回值类型是javabean对象。否则会爆出异常错误。

----详情待更,感谢各位大佬指教更正

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值