Mybatis入门,一篇就够了

2019-10-18  本文已影响0人  我不是刺猬_

1. 为什么需要mybatis?

我们在用JDBC连接数据库时,需要配置Connection,写sql,处理异常等,还会出现很多重复代码,当用了mybatis后,这些都交给它来处理,我们只需要写sql语句,它会提供一些机制来来达到sql的重用。
定义:mybatis是一款持久层框架,支持sql定制、存储过程、高级映射,避免了手动JDBC设置及获取结果集,通过XML配置或注解来将java接口或原生类型或POJO映射到数据库字段,获取数据后封装到对象返回,然后取出数据。

2. DB请求流程

image.png

3.简单例子入门

1)新建项目:eclipse下新建java 项目。
2)配置mybatis数据库连接xml文件:在src目录下新建mybatis-config.xml文件,添加如下内容:

<?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">

<configuration>
//连接配置
    <typeAliases>
        <package name = "com.how2java.pojo"></package>
    </typeAliases>
    <environments default = "development">
        <environment id = "development">
            <transactionManager type = "JDBC"></transactionManager>
            <dataSource type = "POOLED">
                <property name = "driver" value = "com.mysql.jdbc.Driver"></property>
                <property name = "url" value = "jdbc:mysql://localhost:3306/how2java?
charactorEncoding = UTF-8"></property>
                <property name = "username" value = "root"></property>
                <property name = "password" value = "root"></property>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource = "com/how2java/pojo/Category.xml"/> //该文件配置了Category实体类与Category表的映射,
mybatis的数据都是包含在对象的,所以需要一个表的字段对应一个实体类属性,这样就能作为对象返回。我是这样理解的。
    </mappers>
</configuration>

3)创建实体类Category.java: src下新建一个包,此处为com.how2java.pojo

package com.how2java.pojo;

import java.util.List;

public class Category {
    private int id;
    private String name;
    List<Product> products;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4)同一个包下创建对应Category.xml文件

<?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 = "com.how2java.pojo">
     <select id ="listCategory" resultType = "Category">
        select * from category_
    </select>
</mapper> 

5)main方法测试:新建一个测试包com.how2java.test,新建TestMynbatis.java,
需要下载mysql新建一个库how2java,新建表Category_,加入两条id,name数据

package com.how2java.test;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.how2java.pojo.Category;
import com.how2java.pojo.Product;

public class TestMybatis {
    public static void main(String[] args) throws Exception{
        String resource = "mybatis-config.xml";
        InputStream stream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(stream);
        SqlSession session = sessionFactory.openSession();//前边是建立会话过程
        getAll(session);

    private static void getAll(SqlSession session ) {
        List<Category> categorys = session.selectList("listCategory");//参数对应的select语句id
        for(Category c: categorys){
            System.out.println(c.getName());
        }
    }
}

6)运行程序

image.png

4.CURD操作

1)在Category.xml文件中添加操作语句

<select id ="listCategoryById" parameterType = "_int" resultType = "Category">
        select * from category_ where id = #{id}
    </select>
    
    <insert id = "insertCategory" parameterType = "Category">
        insert into category_ (name) values(#{name})
    </insert>
    <delete id = "deletCategory" parameterType = "Category">
        delete from category_  where name = #{name}
    </delete>
    <update id = "updateCategory" parameterType = "Category">
        update category_ set name=#{name} where id = #{id}
    </update>
<!-- 模糊查询 -->
    <select id = "listCategoryByName" parameterType = "String" resultType = "Category">
        select * from Category_ where name like CONCAT('%',#{0},'%')
    </select>
    
    <select id = "listCategoryByIdAndName" parameterType = "map" resultType = "Category">
        select * from Category_ where id > #{id} and name like CONCAT('%',#{name},'%')
    </select>

2)添加如下操作语句

      session.selectOne("listCategoryById", 1);
          
          Category c2 = new Category(); c2.setName("dd");
          session.insert("insertCategory", c2);
          
          Category c3 = new Category(); c2.setName("cc");
          session.delete("deletCategory", c3);
          
          Category c4 = session.selectOne("listCategoryById", 2); 
          c4.setName("ee");
          session.update("updateCategory", c4);
//模糊查询
         List<Category> catList = session.selectList("listCategoryByName", "cc");
          
          for(Category cc: catList) { System.out.println(cc.getName()); }

3)结果

image.png

5.一对多关系关联查询

**1)创建一个新表product_,

use how2java;
create table product_(
id int NOT NULL AUTO_INCREMENT,
name varchar(30)  DEFAULT NULL,
price float  DEFAULT 0,
cid int ,
PRIMARY KEY (id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

插入数据
use how2java;
delete from category_;
INSERT INTO category_ VALUES (1,'category1');
INSERT INTO category_ VALUES (2,'category2');
delete from product_;
INSERT INTO product_ VALUES (1,'product a', 88.88, 1);
INSERT INTO product_ VALUES (2,'product b', 88.88, 1);
INSERT INTO product_ VALUES (3,'product c', 88.88, 1);
INSERT INTO product_ VALUES (4,'product x', 88.88, 2);
INSERT INTO product_ VALUES (5,'product y', 88.88, 2);
INSERT INTO product_ VALUES (6,'product z', 88.88, 2);

2)新建一个产品类Product.java

package com.how2java.pojo;

public class Product {
    private int id;
    private String name;
    private float price;
    
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
}

3)Category.java文件添加属性

package com.how2java.pojo;

import java.util.List;

public class Category {
    private int id;
    private String name;
    List<Product> products;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    //设置产品list
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    
    public List<Product> getProducts(){
        return products;
    }
     @Override
        public String toString() {
            return "Category [id=" + id + ", name=" + name + "]";
        }
}

4)Category.xml文件中添加联表查询语句

<!-- 一对多 -->
    <!-- 返回格式映射,从联合表中取 -->
    <resultMap type = 'Category' id = "categoryBean">
        <id column = "cid" property = "id"/>//联表后column为cid的以id属性显示
        <result column = "cname" property = "name"/>
        
        <collection property = "products" ofType = "Product">//以集合方式显示,设置子元素类型Product,会作为显示,每条子元素包含字段及与关联表映射
            <id  column = "pid" property = "id"/>
            <result  column = "pname" property = "name"/>
            <result  column = "price" property = "price"/>
        </collection>   
    </resultMap>
    
    <select id = "listCategory" resultMap = "categoryBean">//引用 id为categoryBean的resultMap,即上边<resultMap>标签
        select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
    </select>

5)mybatis session对象查询

 List<Category> cs = session.selectList("listCategory"); for (Category c : cs)
          { System.out.println(c); List<Product> ps = c.getProducts(); for (Product p :
          ps) { System.out.println("\t"+p); } }

6)结果:
category_表:

image.png

product_表:

image.png
查询结果:
image.png
解释:xml配置文件中,left join两张表后,resultMap修改了表呈现格式,能映射到则以定义的方式显示,否则只有Category类,没有子集合,如最后两条,这就是一对多的关系。

6.总结

一句话总结mybatis:mybatis就是根据xml配置及存储sql语句的方法来查询数据库的框架。

上一篇下一篇

猜你喜欢

热点阅读