50、Mybatis框架

框架:软件开发中的一套解决方案,不同的框架解决不同的问题。

框架的好处:框架封装了很多的细节,使开发者可以使用极简的方式实现功能,提高开发的效率

 

三层架构:

1、表现层:用于展示数据

2、业务层:用于处理业务需求

3、持久层:用于和数据库交互

 

持久层技术解决方案:

1、JDBC技术:Connection;PreparedStatement;ResultSet,三个对象

2、Spring的JdbcTemplate:对jdbc的简单封装

3、Apache的DBUtils:对jdbc的简单封装

缺点:操作繁琐

 

Mybatis概述:Mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动,创建连接,创建statement等繁杂的过程。

 

Mybatis的入门:

1、mybatis的环境搭建:

            1、创建maven工程并导入jar包

如果使用maven创建工程,可以导入下面坐标:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
</dependency>

            2、创建实体类和dao接口

            3、创建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">
<!-- mybatis的主配置文件-->
<configuration>
    <!-- 配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据的4个基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>

            </dataSource>

        </environment>
    </environments>

    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <mapper resource="lianbang/wu/IUserDao.xml"/>
    </mappers>
</configuration>

            4、创建映射配置文件

<?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 ="lianbang.wu.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll">
        select * from user;
    </select>
</mapper>

注意:映射配置文件和对应的接口包结构要相同;

使用步骤:

public class MybatisTest {
    public static void main(String[] args) throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        //2、创建sqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产sqlSession对象
        SqlSession session = factory.openSession();
        //4、使用sqlSession创建dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5、使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user : users){
            System.out.println(user);
        }
        //6、释放资源
        session.close();
        in.close();

    }
}

 

Mybatis基于注解的使用:

删除映射xml文件,直接在dao接口的方法上使用@Select注解,并且指定SQL语句,同时需要在主配置文件中的mapper配置时,使用class属性指定dao接口的全限定类名。

<mappers>
    <mapper class="lianbang.wu.dao.IUserDao"/>
</mappers>

注意:当实体类和数据库列名不一致时,需要在映射文件中进行对象映射

<resultMap id="userResultMap" type="User">
      <id property="id" column="user_id" />
      <result property="username" column="username"/>
      <result property="password" column="password"/>
</resultMap>

 

Mybatis的CURD:

1、保存数据

映射文件:

<!--保存用户-->
<insert id="saveUser" parameterType="lianbang.wu.domain.User">
    insert  into user (username,address,sex,birthday) value (#{username},#{address},#{sex},#{birthday})
</insert>

测试代码:

public void testSave() throws IOException {
    User user = new User();
    user.setUsername("mybatis");
    user.setAddress("杭州西湖");
    user.setSex("男");
    user.setBirthday(new Date());

    //1、读取配置文件
    InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
    //2、创建sqlSessionFactory工厂
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    //3、使用工厂生产sqlSession对象
    SqlSession session = factory.openSession();
    //4、使用sqlSession创建dao接口的代理对象
    IUserDao userDao = session.getMapper(IUserDao.class);
    //5、使用代理对象执行方法
    userDao.saveUser(user);
    session.commit();
    //6、释放资源
    session.close();
    in.close();
}

2、修改数据

映射文件:

<!--更新用户-->
<update id="updateUser" parameterType="lianbang.wu.domain.User">
    update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id};
</update>

测试代码:

public void testUpdate() throws IOException {
    User user = new User();
    user.setId(51);
    user.setUsername("mybatis_update");
    user.setAddress("杭州西湖");
    user.setSex("男");
    user.setBirthday(new Date());

    //1、读取配置文件
    InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
    //2、创建sqlSessionFactory工厂
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    //3、使用工厂生产sqlSession对象
    SqlSession session = factory.openSession();
    //4、使用sqlSession创建dao接口的代理对象
    IUserDao userDao = session.getMapper(IUserDao.class);
    //5、使用代理对象执行方法
    userDao.updateUser(user);
    session.commit();
    //6、释放资源
    session.close();
    in.close();
}

3、删除数据

映射文件:

<!--删除用户-->
<delete id="deleteUser" parameterType="Integer">
    delete from user where id=#{userid};
</delete>

测试代码:

public void testDelete() throws IOException {
        Integer uid = 51;
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        //2、创建sqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产sqlSession对象
        SqlSession session = factory.openSession();
        //4、使用sqlSession创建dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5、使用代理对象执行方法
        userDao.deleteUser(uid);
        session.commit();
        //6、释放资源
        session.close();
        in.close();
    }

 

Mybatis中的连接池:

Mybatis连接池提供了3种方式的配置:

主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式

type属性的取值:POOLED,采用传统的javax.sql.DataSource规范中的连接池,Mybatis中有针对规范的实现

                        UNPOOLED,采用传统的获取连接的方式,虽然也实现了实现了javax.sql.DataSource接口,但是并没有使用池的思想

                        JNDI,采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到的DataSource是不一样的

                                  如果不是Web或者Maven的war工程,是不能使用的

                                  使用tomcat服务器,采用的连接池就是dbcp连接池。

 

mybaits中的事务:

sqlsession的commit和rollback;

session.commit();
session.rollback();

mybaits中的动态sql语句:

if标签:

<select id="findByCondition" resultType="lianbang.wu.domain.User" parameterType="lianbang.wu.domain.User">
    select * from user  where  1=1
    <if test="userName != null">
         and username = #{userName}
    </if>
</select>

where标签:

<select id="findByCondition" resultType="lianbang.wu.domain.User" parameterType="lianbang.wu.domain.User">
    select * from user
    <where>
        <if test="userName != null">
            and username = #{userName}
        </if>
    </where>

</select>

foreach标签:

<select id="findByRange" parameterType="queryvo" resultType="lianbang.wu.domain.User">
    select * from user
    <where>
        <if test="id!=null and ids.size()>0">
            <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </if>
    </where>
</select>

sql标签:

<sql id="defauleUser">
    select * from user
</sql>

<select id="findAll" resultType="lianbang.wu.domain.User">
    <include refid="defaule">
        
    </include>i
</select>

 

Mybatis的多表查询

一对一的查询:

方法一:新建一个包含两个对象所有成员变量的实现类,将查询结果封装到里面

方法二:在其中一个对象中,添加另一个对象到成员变量中。在映射文件中,对变量进行如下映射

<resultMap id="accountUserMap" type="lianbang.wu.domain.Account">
    <id property="id" column="aid"></id>
    <result property="uid" column="uid"></result>
    <result property="money" column="money"></result>

    <association property="user" column="uid" javaType="lianbang.wu.domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
    </association>
</resultMap>

再将查询结果封装到对应的对象中。

 

一对多的查询:

<resultMap id="accountUserMap" type="lianbang.wu.domain.Account">
    <id property="id" column="aid"></id>
    <result property="uid" column="uid"></result>
    <result property="money" column="money"></result>

  

    <collection property="emplist" ofType="lianbang.wu.domain.emp">
        <id column="eid" property="id"></id>
        <result column="ename" property="name"></result>
    </collection>


</resultMap>

多对多查询:

等同一对多

延迟加载:

概念:在真正使用数据的时才发起查询,不用的时候不查询,按需加载(懒加载),通常在一对多查询或多对多查询使用

立即加载:

概念:不管用不用,只要一调用方法,马上发起查询,通常在一对对或多对多查询使用

实现步骤:

1、开启延迟加载:主配置文件中设置

<settings>
    <setting name="lazyLoadingEnable" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

2、设置延迟加载的ResultMap

<resultMap id="accountUserMaplazyLoad" type="lianbang.wu.domain.Account">
    <id property="id" column="aid"></id>
    <result property="uid" column="uid"></result>
    <result property="money" column="money"></result>

  

    <collection property="emplist" ofType="lianbang.wu.domain.emp">
        <id column="eid" property="id"></id>
        <result column="ename" property="name"></result>
    </collection>


</resultMap>

3、延迟加载的mapper文件:

<select id="accountUserMapLazy" resultMap="accountUserMapLazyLoad">
select * from account
</select>

<select id ="findUser" parameterType="id" resultType="User">
select * from user where id = #{value}
</select>

缓存:

概念:存在于内存中的临时数据

作用:减少和数据库的交互次数,提高执行效率

适用于:经常查询并且不经常改变的,数据的正确与否对最终结果影响不大的

不适用于:经常改变的数据,数据的正确与否对最终的结果影响很大的,例如:商品的库存,银行的汇率,股市的牌价

mybatis中的一级缓存:它指的是Mybatis中sqlSession对象的缓存,当我们执行查询之后,查询的结果会同时存入到sqlSession为我们提供的一块区域中,该区域的结构是一个Map,当我们再次查询同样的数据,mybatis会先去sqlSession中查询是否有,有的话直接拿出来用,当sqlSession对象消失,mybatis的一级缓存也就消失了。

注意:当sqlSession执行修改,添加,删除,commit,close等方法时,就会清空一级缓存。

mybatis中的二级缓存:它指的是mybatis中的sqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的sqlSession共享其缓存。

二级缓存的使用步骤:

第一步:让mybatis框架支持二级缓存,在主配置文件中配置

<setting name ="cacheEnabled" value="true"/>

第二步:让当前的映射文件支持二级缓存

<cache></cache>

第三步:让当前的操作支持二级缓存

创建多个session对象。注意被实体类要实现序列化接口。

 

注解开发:

在mybatis中,针对CRUD一共有四种注解:@Select@Insert@Update@Delete

@Select("select * from user")
@Results({
@Result(id = true,column ="id",property = "id"),
@Result(column = "name", property = "name")})
List<User> findAll();

多表查询

一对一

@Select("select * from user")
@Results({
@Result(id = true,column ="id",property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "deptid",property = "dept",one=@One(select = "lianbang.wu.dao.IDeptDao.selectdetpBydi"))
})
List<User> findAll();

 

一对多:

@Select("select * from user")
@Results({
@Result(id = true,column ="id",property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "deptid",property = "dept",many=@Many(select = "lianbang.wu.dao.IDeptDao.selectdetpBydi"))
})
List<User> findAll();

二级缓存

@CacheNamespace(blocking = true)

 

转载于:https://my.oschina.net/u/4131739/blog/3083019

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值