栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis

目录

MyBatis步骤

1、核心配置文件mybatis-config.xml

2、创建工具类生成sqlSession

3、创建Mapper(Dao)接口类 

4、创建Mapper.xml配置文件

5、测试

二、万能Map

三、核心配置文件mybatis-config.xml

1、mappers元素:映射器 : 定义映射SQL语句文件      

2、环境配置(事务管理器)

3、属性(properties)

4、类型别名

5、调整设置

四、SqlSession生命周期和作用域

1、 SqlSessionFactoryBuilder

2、 SqlSessionFactory :

3、SqlSession:

五、解决属性名和字段不一致的问题

六、日志

1、日志工厂

2、Log4j

3、使用步骤:

七、分页

1、使用Limit实现分页

2、RowBounds分页 

3、分页插件:PageHelper 

八、注解开发

#与$的区别

九、Mybatis详细的执行流程  

十、Lombok

十一、数据库关系多对一处理

1、多对一 

2、一对多

十二、动态SQL

1、if标签

2、where标签

3、set标签

4、trim

5、choosewhenotherwise标签

6、sql片段

7、foreach标签

十三、缓存

1、缓存:

2、Mybatis缓存

3、一级缓存

4、二级缓存

5、缓存原理:

6、自定义缓存ehcache


MyBatis步骤

1、核心配置文件mybatis-config.xml

       在src/main/resources中创建mybatis-config.xml作为核心配置文件,内涵数据库连接信息,同时也需要在该文件中使用mapper为每一个Mapper.xml注册




    
        
            
            
                
                
                
                
            
        
    
    
        
    

2、创建工具类生成sqlSession

         在src/main/java中创建一个utils工具包,创建了一工具类生成sqlSession,sqlSession就是Mybatis中数据库连接对象
       通过 UserMapper mapper = sqlSession.getMapper(UserMapper.class);可以直接获取对应的接口对象,sqlSession.commit():提交事务。sqlSession.close():关闭数据库连接。

package utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
   private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
//            先获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
//        根据sqlSessionFactory.openSession()获取到sqlSession
//        将sqlSession返回
        return  sqlSessionFactory.openSession();
    }

}

3、创建Mapper(Dao)接口类 
public interface UserMapper {

User getUserById(int id);
int addUser(User user);
int deleteUser(int id);
int updateUser(User user);

}

4、创建Mapper.xml配置文件

        创建Mapper接口类对应的Mapper.xml配置文件,顶替原先的Impl实现类。 





//select对应查询,insert对应插入,delete对应删除,update对应修改
//resultType设置返回类型,resultMap设置结果集类型,parameterType设置参数类型,parameterMap设置参数及类型,#{}可以直接获取对应的值,替代jdbc中的?号
   
            select id,name,pwd as password from user where id=#{id}
        
方式二:resultMap结果集映射
        
            
        
                
                
                
            
            
select * from user

          2.3、测试类

        在这里,我们需要使用RowBounds类

@Test
public void testUserByRowBounds() {
  SqlSession session = MybatisUtils.getSqlSession();
  int currentPage = 2;  //第几页
  int pageSize = 2;  //每页显示几个
  RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);
  //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
  List users = session.selectList("mapper.UserMapper.getUserByRowBounds", null, rowBounds);
  for (User user: users){
      System.out.println(user);
 }
  session.close();
}

3、分页插件:PageHelper 

八、注解开发

        注意:利用注解开发就不需要mapper.xml映射文件了

       使用注解开发只能在核心配置文件中使用class一个个导入接口,使用.xml开发可以直接使用resource配置*.xml配置所有.xml文件


        1、我们在我们的接口中添加注解           

//如果有多个基本数据类型参数,每个参数都需要使用注解@Param("")说明
@Select("select id,name,pwd password from user where id=#{id} and name=#{name}")
 User getUserById(@Param("id") int id,@Param("name") String name);

        2、在mybatis的核心配置文件中注入       


    

        3、测试

@Test
   public  void getUserById(){
//        获取sqlSession
       SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行sql
       UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       User userById = mapper.getUserById(2,"张三");
       System.out.println(userById);
       sqlSession.close();
   }

        4、利用Debug查看本质

        5、本质上利用了JVM动态代理机制

        6、设置事务自动提交

//获取SqlSession连接
public static SqlSession getSession(){
  return sqlSessionFactory.openSession(true);
}

@Param注解用于给方法参数起一个名字。以下是总结的使用原则:

在方法只接受一个参数的情况下,可以不使用@Param。

在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。

如果参数是JavaBean,则不能使用@Param。

不使用@Param注解时,参数只能有一个,并且是Javabean。

使用注解和配置文件协同开发,才是MyBatis的最佳实践!


#与$的区别


#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】

INSERT INTO user (name) VALUES (#{name});
INSERT INTO user (name) VALUES (?);


${} 的作用是直接进行字符串替换

INSERT INTO user (name) VALUES ('${name}');
INSERT INTO user (name) VALUES ('kuangshen'); 

九、Mybatis详细的执行流程  

十、Lombok

使用步骤:
1、IDEA安装插件Lombok
2、在pom中导入Lombok包
3、以下注解及生成的方法

 @Getter:get方法
  @Setter:set方法
  @FieldNameConstants:Fields
  @ToString:toString方法
  @EqualsAndHashCode:equals、hashCode、canEqual
  @AllArgsConstructor:全参构造器, @RequiredArgsConstructor and @NoArgsConstructor:空参构造器
  @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
  @Data :无参构造、get、set、toString、hashcode、equals
  @Builder
  ...

十一、数据库关系多对一处理

​​​​​​​多个学生对应一个老师,学生数据库表中设置老师的id的外键
对于学生,多对一的现象,从学生这边关联一个老师!
对于老师而言,集合,一对多现象 

1、多对一 

    多个学生对应一个老师。设计:学生数据库表中设置老师的id的外键,Student有Teacher teacher属性
        查询方式一:按查询嵌套处理

    
     select id,name,tid from student
    
    
        
        
        
        
    
    
        select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id


        
        
          
        
             
             
        

 

2、一对多

        一个老师拥有多个学生。设计:学生数据库表中设置老师的id的外键,Teacher中设置List students属性
        查询方式一:按查询嵌套处理


    select id,name,tid from student where tid=#{id}

        方式二:按结果嵌套处理


    select * from blog where 1=1
    
        and title=#{title}
    
    
        and author=#{author}
    

2、where标签

        作用和where一样。拼接语句中的and会自动处理,第一个参数处的and删除,后面的保存


    select * from blog
    
        
            and title=#{title}
            and views=0
        
    

6、sql片段

        某个sql语句用的特别多,为了增加代码的重用性,将这些代码抽取出来,然后使用时直接调用。
        提取SQL片段:


   
      title = #{title}
   
   
      and author = #{author}
   

        引用SQL片段:


  select * from blog
   
       
       
          id=#{id}
       
   

十三、缓存

​​​​​​​1、缓存:

1、什么是缓存 [ Cache ]?

        存在内存中的临时数据。
        将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2、为什么使用缓存?

        减少和数据库的交互次数,减少系统开销,提高系统效率。

3、什么样的数据能使用缓存?

        经常查询并且不经常改变的数据。

2、Mybatis缓存

        MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
       默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
       二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
       为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

3、一级缓存

   一级缓存也叫本地缓存:
    与数据库同一次会话期间查询到的数据会放在本地缓存中。
    以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
    一级缓存是SqlSession级别的缓存
    测试:

    @Test
    public  void getUserById(){
//        获取sqlSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(2);
        System.out.println(userById);
        User userById1 = mapper.getUserById(2);
        System.out.println(userById1);
        System.out.println(userById1==userById);
        sqlSession.close();
    }

   输出为:

    ==>  Preparing: select * from user where id=?
    ==> Parameters: 2(Integer)
    <==    Columns: id, name, pwd
    <==        Row: 2, 张三, 1233
    <==      Total: 1
    User(id=2, name=张三, password=1233)
    User(id=2, name=张三, password=1233)
    true

可以看出第二次没有进数据库搜索,并且两次搜索的对象是同一个。
缓存失效的情况:

1、sqlsession不同
2、增删改操作可能会改变原来数据,所以必定刷新缓存,即使查询的数据没有改变
3、sqlsession相同,查询语句(数据)不同
4、sqlSession相同,手动清除一级缓存:session.clearCache();

4、二级缓存

二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

工作机制:

   一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    新的会话查询信息,就可以从二级缓存中获取内容;
    不同的mapper查出的数据会放在自己对应的缓存(map)中;

使用步骤:
    1、开启全局缓存 【mybatis-config.xml】
     

 

    2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;
 

【xxxMapper.xml】FIFO先进先出缓存,


  这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
    3、测试:

@Test
public  void getUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    SqlSession sqlSession1 = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);

    User user= mapper.getUserById(2);
    System.out.println(user);
    sqlSession.close();

    User user1 = mapper1.getUserById(2);
    System.out.println(user1);
    System.out.println(user1==user);
    sqlSession1.close();
}

    结论:
        查出的数据都会被默认先放在一级缓存中
        只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

5、缓存原理:

每个sqlsession向数据库访问,然后将数据缓存在该sqlsession下的一级缓存中
如果某个sqlsession关闭,该sqlsession中的一级缓存中的内容放在对应Mapper.xml下的二级缓存中。
一级缓存是SqlSession级别的缓存
二级缓存是Mapper.xml级别的缓存

查询顺序:先查看二级缓存,再查看一级缓存,最后查数据库


6、自定义缓存ehcache

Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;
        1、要在应用程序中使用Ehcache,需要引入依赖的jar包

    
       org.mybatis.caches
       mybatis-ehcache
       1.1.0
    

        2、在mapper.xml中使用对应的缓存即可

  

        3、编写ehcache.xml文件,如果在加载时未找到/ehcache.xml资源或出现问题,则将使用默认配置。

 
    
   
   

   

   
   
   

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号