mybatis

介绍

概述
    MyBatis最早源自Apache基金会的一个开源项目iBatis.
    2010年这个项目由Apache software foundation迁移到google code,并且改名为MyBatis;
    MyBatis是支持普通SQL查询,存储程和高级映射的优秀持久层框架。
    MyBati封装了几乎所有的JDBC代码和参数的手工设置以及结果集的检索;
    MyBatist使用简单的XML或注解做配置和定义映射关系将Java的POJOs(Plain Old Java Objects)映射成数据库中的记录.
下载
    http://www.mybatis.org/mybatis-3/
Mybatis体系结构
    1.加载配置:配置来源于两个地方,一处是配置文件,一处是Java代码的注解,将SQL的配置信息加载成为一个个MappedStatement对象(包括了传入参数映射配置、执行的SQL语句、结果映射配置),存储在内存中。
    2.SQL解析:当API接口层接收到调用请求时,会接收到传入SQL的ID和传入对象(可以是Map、JavaBean或者基本数据类型),Mybatis会根据SQL的ID找到对应的MappedStatement,然后根据传入参数对象对MappedStatement进行解析,解析后可以得到最终要执行的SQL语句和参数。
    3.SQL执行:将最终得到的SQL和参数拿到数据库进行执行,得到操作数据库的结果。
    4.结果映射:将操作数据库的结果按照映射的配置进行转换,可以转换成HashMap、JavaBean或者基本数据类型,并将最终结果返回。
MyBatis配置文件
    MyBatis框架的XML配置文件包含下面两种类型
        1.mybatis-config.xml (1个)
            主配置文件,用于指定数据库连接参数和框架参数
            在mybatis官网查看http://www.mybatis.org/mybatis-3/getting-started.html
        2.DepartmentMapper.xml (n个)
            映射定义文件,用于定义SQL语句和映射信息
            在mybatis官网查看http://www.mybatis.org/mybatis-3/sqlmap-xml.html
框架API简介 
    SqlSessionFactoryBuilder
        该对象负责根据MyBatis配置文件mybatis-config.xml构建SqISessionFaciory实例
    SqlSessionFactory
        每一个MyBatis的应用程序都以一个SqISessionFactory对象为核心。该对象负责创建SqlSession对象实例
    SqlSession
        该对像包含了所有执行SQL操作的方法,用于执行己映射的SQL语句
使用步骤
    1.为工程添加MyBatis开发包( mybatis-x.x.x.jar )和数据库驱动包
    2.在src下添加MyBatis配置文件SqIMapConfig.xml
    3.修改SqIMapConfig.xml指定数据库连接参数
    4.利用MyBatis API编程,获取SqISession实例

mybatis

第一种方式步骤
    1.maven引入依赖包
        
            org.mybatis
            mybatis
            3.4.4
        
        
            mysql
            mysql-connector-java
            5.1.26
        
    2.创建mybatis-config.xml
        
        
        
          
            
              
              
                
                
                
                
              
            
          
          
            
          
        
    3.创建数据库表/创建实体类
        public class User {
            private int id;
            private String name;
            private int age;
        }
    4.创建实体类配置文件(xml)
        
        
        
            
                insert into user (id,name,age) values (#{id},#{name},#{age})
            
        
    5.测试
        public void test() throws Exception{
            String resource = "mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setName("xxx");
            user.setAge(10);
            sqlSession.insert(User.class.getName()+".insert",user);
            sqlSession.commit();
            sqlSession.close();
        }
第二种方式步骤
    1.maven引入依赖包
    2.创建mybatis-config.xml
    3.创建数据库表/创建实体类
    4.创建实体类Mapper接口
        public interface UserDao {
            public void insert(User user);
        }
    5.创建实体类配置文件(xml)
        
        
        
            
                insert into user (id,name,age) values (#{id},#{name},#{age})
            
        
    6.测试
        public void test() throws Exception{
            String resource = "mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setName("xxx");
            user.setAge(10);
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            mapper.insert(user);
            sqlSession.commit();
            sqlSession.close();
        }

加载配置文件

mybatis-config.xml
    
        
    

增删改查/分页查询

注意:增加/删除/修改 都可以使用update方法?
增加
    
        insert into user (id,name,age) values (#{id},#{name},#{age})
    
    sqlSession.insert(User.class.getName()+".insert",user);
    增加时返回id
    
        insert into teacher (name,age) values(#{name},#{age})
    
    Teacher teacher = new Teacher();
    teacher.setName("shuaige");
    teacher.setAge(20);
    sqlSession.insert(Teacher.class.getName()+".insert", teacher);
    System.out.println(teacher.getId());
    注意:
        useGeneratedKeys="true" 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的主键字段中
        keyProperty="id"  指定JavaBean的主键字段
删除
    
        delete from user where id=#{id}
    
    sqlSession.delete(User.class.getName()+".delete",user);
    
        delete from user where id=#{id}
    
    sqlSession.delete(User.class.getName()+".delete",7);
修改
    
        update user set name=#{name},age=#{age} where id=#{id}
    
    sqlSession.update(User.class.getName()+".update",user);
查询
    根据id查询
        
        User user = sqlSession.selectOne(User.class.getName()+".getById", 8);
    根据名字模糊查询
        
        List list = sqlSession.selectList(User.class.getName()+".getByName", "%shuaige%");
    分页查询
        
        Map dataMap = new HashMap();
        dataMap.put("name", "%shuaige%");
        dataMap.put("start", 0);
        dataMap.put("size", 3);
        List list = sqlSession.selectList(User.class.getName()+".getByPage", dataMap);
        第二种
            
            RowBounds bounds = new RowBounds(0,5);
            List list = sqlSession.selectList(User.class.getName()+".getLimit", bounds);

别名配置

在主配置文件中定义类的别名
    
        
    
映射文件中的resultType和parameterType就可以改为使用别名了
    
    
注意:不区分大小写

定义结果集

在映射文件中定义结果集
    
        
        
        
    
在映射文件中使用结果集
    
测试
    Map dataMap = new HashMap();
    dataMap.put("name", "%shuaige%");
    dataMap.put("start", 3);
    dataMap.put("size", 3);
    List list = sqlSession.selectList(User.class.getName()+".getByPage", dataMap);
注意:
    重点在配置关联映射的时候使用

动态SQL(增删改查/分页查询)

总结
    sql/trim/if/foreach/where/set/choose/when/otherwise
注意:
    > 换为 >
    < 换为 <
增加
    
        
            
                name,
            
            
                age,
            
            
                birth,
            
        
    
    
        
            
                #{name},
            
            
                #{age},
            
            
                #{birth},
            
        
    
    
        insert into user () values ()
    
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setName("shuaige");
        sqlSession.update(User.class.getName()+".dinsert", user);
        sqlSession.commit();
        sqlSession.close();
    }
修改
    
        update user
        
            
                name=#{name},
            
            
                age=#{age},
            
            
                birth=#{birth}
            
        
        where id=#{id}
    
    public static void test5() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setId(23);
        user.setName("shuaige35");
        user.setAge(35);
        user.setBirth(new Date());
        sqlSession.update(User.class.getName()+".dupdate", user);
        sqlSession.commit();
        sqlSession.close();
    }
删除
    
        delete from user where id in
        
            #{ids}
        
    
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int[] arr = new int[]{1,2,3};
        sqlSession.delete(User.class.getName()+".ddelete", arr);
        sqlSession.commit();
        sqlSession.close();
    }
查询
    
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Map dataMap = new HashMap();
        dataMap.put("name", "%shuaige%");
        dataMap.put("age", 30);
        List list = sqlSession.selectList(User.class.getName()+".dget", dataMap);
        sqlSession.commit();
        sqlSession.close();
    }
    
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List list = new ArrayList();
        list.add(4);
        list.add(5);
        list.add(6);
        List list2 = sqlSession.selectList(User.class.getName()+".dgetIds", list);
        sqlSession.commit();
        sqlSession.close();
    }

关联操作

双向关联(多对多)
    sql:
        create table teacher(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table student(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table tea_stu(
            id int primary key auto_increment,
            t_id int,
            s_id int,
            constraint fk_teacher_id foreign key(t_id) references teacher(id),
            constraint fk_student_id foreign key(s_id) references student(id)
        );
    配置
        Teacher.xml
            
                
                
                
            
            
                
            
            
            
                insert into teacher (name,age) values(#{name},#{age})
            
        Student.xml
            
                
                
                
            
            
                
            
            
            
                insert into student (name,age) values(#{name},#{age})
            
    代码
        插入
            Teacher teacher = new Teacher();
            teacher.setName("帅哥");
            Student student = new Student();
            student.setName("小明");
            teacher.getStudents().add(student);
            Student student1 = new Student();
            student1.setName("小明1");
            teacher.getStudents().add(student1);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            for(Student stu : teacher.getStudents()){
                TeaStu ts = new TeaStu();
                ts.setStudent(stu);
                ts.setTeacher(teacher);
                sqlSession.insert(Student.class.getName()+".insert", stu);
                sqlSession.insert(TeaStu.class.getName()+".insert", ts);
            }
        查询
            List selectList = sqlSession.selectList(Student.class.getName()+".getAll", 1);
            List selectList1 = sqlSession.selectList(Teacher.class.getName()+".getAll", 1);
双向关联(一对多)
    sql:
        create table teacher(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table student(
            id int primary key auto_increment,
            name varchar(20),
            age int,
            t_id int,
            constraint fk_tea_id foreign key(tid) references teacher(id)
        );
    配置
        
            insert into teacher (name,age) values(#{name},#{age})
        
        
            insert into student (name,age,t_id) values(#{name},#{age},#{teacher.id})
        
    代码
        插入
            Teacher teacher = new Teacher();
        teacher.setName("帅哥");
            Student stu = new Student();
            stu.setName("小红");
            stu.setTeacher(teacher);
            Student stu1 = new Student();
            stu1.setName("小明");
            stu1.setTeacher(teacher);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            sqlSession.insert(Student.class.getName()+".insert", stu);
            sqlSession.insert(Student.class.getName()+".insert", stu1);
        动态插入配置
            
                
                    
                        name,
                    
                    
                        age,
                    
                    
                        t_id,
                    
                
            
            
                
                    
                        #{name},
                    
                    
                        #{age},
                    
                    
                        #{teacher.id},
                    
                
            
            
                insert into student () values()
            
        查询多的一端
            Student.xml
                
                    
                    
                    
                    
                
                
            Teacher.xml
                
            java代码
                Student stu = sqlSession.selectOne(Student.class.getName()+".getStudentfetchTeacher", 1);
        查一的一端
            Student.xml
                
                    
                    
                    
                
            Teacher.xml
                
                    
                    
                    
                
                
                    
                
                
            java代码
                List selectList = sqlSession.selectList(Teacher.class.getName()+".getAllById", 1);
双向关联(一对一)
    sql:
        create table teacher(
            id int not null auto_increment comment '主键',
            name  varchar(20) not null default '' comment '姓名',
            age int not null default 0 comment '年龄',
            primary key(id)
        )engine=innoBD default charset=utf8;

        create table student(
            id int not null auto_increment comment '主键',
            name varchar(20) not null default '' comment '姓名',
            age int not null default 0 comment '年龄',
            t_id int not null,
            primary key(id),
            constraint fk_teacher_id foreign key (t_id) references teacher(id)
        )engine=innoDB default charset=utf8;
    映射文件
        Teacher.xml
            
                
                
                
                
            
            
                insert into teacher (name,age) values (#{name},#{age})
            
            
        Student.xml
            
                
                
                
            
            
                insert into student (name,age,t_id) values (#{name},#{age},#{teacher.id})
               
            
    测试
        增加
            Teacher teacher = new Teacher();
            teacher.setName("帅哥");
            teacher.setAge(30);
            Student student = new Student();
            student.setName("小明");
            student.setAge(20);
            student.setTeacher(teacher);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            sqlSession.insert(Student.class.getName()+".insert", student);
        查询
            Teacher teacher = sqlSession.selectOne(Teacher.class.getName()+".getOne", 1);

返回Map类型

ResultType="java.util.HashMap"
Map map = (Map)session.selectOne()

返回list集合/map集合


时间排序查询


集合操作

List集合
    sql:
        create table users(
            id int primary key auto_increment comment '主键',
            name varchar(20) not null default '' comment '姓名'
        )engine=innoDB default charset=utf8;

        create table address(
            id int primary key auto_increment comment '主键',
            address varchar(20) not null default '' comment '地址',
            u_id int not null,
            constraint fk_user_address foreign key (u_id) references users(id)
        )engine=innoDB default charset=utf8;
    User.xml
        
            
                
                
                
            
            
                insert into users (name) values (#{name})
            
            
        
    User.java
        public class User implements Serializable{
            private static final long serialVersionUID = 4980066222353642286L;
            private int id;
            private String name;
            private List address = new ArrayList();
        }
    Address.xml
        
            
                
            
            
                insert into address (address,u_id) values (#{address},#{user.id})
            
            
        
    Address.java
        public class Address {
            private int id;
            private String addr;
            private User user;
        }
    插入
        User user = new User();
        user.setName("帅哥");
        user.getAddress().add("北京");
        user.getAddress().add("广州");
        sqlSession.insert(User.class.getName()+".insert",user);
        for(String str : user.getAddress()){
            Address address = new Address();
            address.setAddress(str);
            address.setUser(user);
            sqlSession.insert(Address.class.getName()+".insert", address);
        }
    查询
        User user = sqlSession.selectOne(User.class.getName()+".getOne", 1);
Set集合
    sql:
        create table user(
            id int primary key auto_increment comment '主键',
            name varchar(20) not null default '' comment '姓名'
        )engine=innoDB default charset=utf8;
        create table address(
            addr varchar(20) not null default '' comment '地址',
            u_id int not null comment '外键',
            constraint fk_u_a_id foreign key (u_id) references user(id)
        )engine=innoDB default charset=utf8;
    User.xml
        
            
                
                
                
            
            
                insert into user (name) values (#{name})
            
            
        
    User.java
        public class User implements Serializable{
            private static final long serialVersionUID = 4980066222353642286L;
            private int id;
            private String name;
            private Set address = new HashSet();
        }
    Address.xml
        
            
                
            
            
                insert into address(addr,u_id) values (#{addr},#{user.id})
            
        
    Address.java
        public class Address {
            private String addr;
            private User user;
        }
    测试
        插入
            User user = new User();
            user.setName("帅哥");
            user.getAddress().add("北京");
            user.getAddress().add("广州");
            sqlSession.insert(User.class.getName()+".insert",user);
            for(String str : user.getAddress()){
                Address address = new Address();
                address.setAddr(str);
                address.setUser(user);
                sqlSession.insert(Address.class.getName()+".insert", address);
            }
        查询
            User user = sqlSession.selectOne(User.class.getName()+".getOne", 1);
Map集合
    

继承操作


延迟加载


mybatis与java数据类型映射


缓存

一级缓存
    session
二级缓存
    开启二级缓存mybatis-config.xml
        
            
                
            
        
    Teacher.java
        注意:此类一定要实现Serializable接口
    映射文件Teacher.xml
        
            
        
        注意:
            默认所有的查询都支持(建议仅仅用单条记录查询)
            size: 内存中支持的最大对象数量
            eviction: 替换策略: FIFO  LRU
            flushInterval: 设置刷新的时间间隔, 如果没有配置则 发送SQL语句的时候及时更新

定义数据处理器???!!(需要再处理)

创建日期处理器
    public class DateTypeHandler implements TypeHandler {
        public String getResult(ResultSet rs, String columnName) throws SQLException {
            Date value = rs.getTimestamp(columnName);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.format(value);
        }
    }
在全局映射文件mybatis-config.xml配置处理器
    
        
    
    
        
    
在映射文件中使用
    
        
    
注意:做专门的数据显示处理

你可能感兴趣的:(mybatis)