MyBatis小案例完善增强

https://blog.csdn.net/techbirds_bao/article/details/9233599

上链接为一个不错的Mybatis进阶博客

 

当你把握时间,时间与你为伍.

将上一个简单的小案例完善,加入了更多的数据库SQL mapper映射

------------ 其后还有继续更新,如动态mapper映射,动态SQL.(不知道是否为同一个意思,总之mapper就是为了将sql语句给数据库做交互)

 多功能的primary3案例源码  <<注意获取SqlSession有错误,应该是获取SqlSessionFactory,再每个方法获取session.事务相关

加入了一些新的方法,小工具似的方法如将mapper.xml中的某段sql语句包装起来使用.(在该语句重复多次情况下)

以及当方法含有多个参数时,mapper.xml中的sql语句可以使用#{ 0 }, #{ 1 }这样的下标位置获取.

以及动态SQL,当有哪些数据时,或者满足给定条件时,再执行sql语句的where条件.

还有传入数组以及list查询符合这些id的foreach.以及自定义类型的foreach.

具体测试类如下:

package com.ykmimi.dao;

import java.util.List;
import java.util.Map;

import com.ykmimi.entity.Student;

public interface IStudentDao {
    //插入数据库新的学生实例
    void insertStudent(Student student);
    //插入数据库新的学生实例并包含id默认设置
    void insertStudentCacheId(Student student);
    
    //删除学生元组通过学生id
    void deleteStudentById(int id);
    //更新学生信息(设置更改内容到student对象,并最后设置要修改的学生id)
    void updateStudent(Student student);
    
    //查询所有学生实例 返回List
    List<Student> selectAllStudents();
    //查询单个学生实例
    Student selectStudentById(int id);
    //查询多个学生实例根据模糊查询name
    List<Student> selectStudentsByName(String name);
    
    //多条件查询,根据名字以及年龄多少 参数map
    List<Student> selectStudentsByCondition(Map<String, Object> map);
    
    //多条件查询,根据名字和分数, 参数多个
    List<Student> selectStudentsByConditionB(String name,double score);
    
    //动态SQL
    List<Student> selectStudentsByConditionC(Student student);
    //根据switch,case类型查询,符合其中一个when则就不执行其他的条件
    List<Student> selectStudentsByChoose(Student student);
    //根据数组查询
    List<Student> selectStudentsByForeach(int[] ids);
    //根据list查询
    List<Student> selectStudentsByForeach2(List<Integer> ids);
    //根据泛型自定义的list查询
    List<Student> selectStudentsByForeach3(List<Student> ids);
    //包装起来的sql语句片段
    List<Student> selectStudentsBySqlFragment(List<Student> ids);
}

通过此段学习,得知MyBatis就是对SQL的封装.而其功能语句也是固定化的.(某些)

案例包中的查询均通过.

下篇将整合一下最近的MyBatis学习.做个小段总结.

 

3Q

-------------------------------------------------------------------------

Dao的实现类其实并没有干什么实质性的工作,它仅仅就是通过SqlSession的相关API定位到映射文件 mapper 中相应的
id的SQL语句,真正对DB进行操作的工作其实是由框架通过 mapper 中的 SQL 完成的.
MyBatis框架抛开了 Dao 的实现类, 直接定位到映射文件 mapper 中的相应 SQL 语句, 对DB进行操作.
这种对Dao的实现方式称为 Mapper 的动态代理方式.
Mapper动态代理方式无需程序员实现Dao接口,接口是由MyBatis结合映射文件自动生成的动态代理实现的.
------------------------------------------------------------------------

 

posted @ 2018-08-13 10:37  ukyo--夜王  阅读(164)  评论(0编辑  收藏  举报