mybatis入门

5 篇文章 0 订阅
5 篇文章 0 订阅

mybatis认识

MyBatis是一个ORM的数据库持久化框架,它以映射sql语句orm方式来数据库持久化操作。

ORM:对象关系映射(Object Relational Mapping,简称ORM),是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。

常见的ORM持久化框架

  • 1.JPA:本身是一种ORM规范,不是ORM框架.由各大ORM框架提供实现。
  • 2.Hibernate:目前最流行的ORM框架.设计灵巧,性能一般(自己去控制性能,不是很好控制),文档丰富.(完全自动操作);
    Hibernate是一个完整的ORM框架,常规CRUD我们不需要写一句SQL;
    jpa:完整orm映射规范;
    hibernate:是整orm映射规范的一种实现;
    DataJpa:对jpa的操作进行封装,让我们使用更加简单。
  • 3.MyBatis:本是apache的一个开源项目iBatis,提供的持久层框架包括SQL Maps(Mapper)和Dao,允许开发人员直接编写SQL(更好灵活).(Sql操作方式)。
    MyBatis 并不是一个完整的ORM框架,因为我们还需要自己去写全部SQL。

MyBatis入门-简单实现

使用最原生的mybatis,步骤:

public List<Product> selectAll() throws IOException {
        //把核心配置文件转为io流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactory对象  就相当于jpa的EntityManagerFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession  就相当于jpa的EntityManager
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //statement 定位mybatis我要去查询哪条sql语句(namespace+id)
        String statement = "cn.itsource.mybatis._01hello.dao.IProductDao.selectAll";
        //查询
        List<Product> products = sqlSession.selectList(statement);
        //关闭资源
        return products;
    }

导包

mybatis导包

配置文件

准备jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=root

准备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>
    <!-- 引入外部资源文件 -->
    <properties resource="jdbc.properties"></properties>
    <!--配置全限定名对应的别名-->
    <typeAliases>
        <typeAlias type="com.cl.mybatis._02_mapper.damain.Employee" alias="Employee"></typeAlias>
        <typeAlias type="com.cl.mybatis._02_mapper.query.EmployeeQuery" alias="EmployeeQuery"></typeAlias>
    </typeAliases>

    <!-- 配置环境:可以配置多个环境,default:配置某一个环境的唯一标识,表示默认使用哪个环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <!--事务类型-->
            <transactionManager type="JDBC"/>
            <!--连接池-->
            <dataSource type="POOLED">
                <!-- 配置连接信息 -->
                <property name="driver" value="${jdbc.driverClass}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <mapper resource="com/cl/mybatis/_01/dao/impl/ProductDaoImpl.xml"/>
        <mapper resource="com/cl/mybatis/_02_mapper/mapper/EmployeeMapper.xml"/>
    </mappers>

</configuration>

准备相应的表

/*
MySQL Data Transfer
Source Host: localhost
Source Database: mysqltest
Target Host: localhost
Target Database: mysqltest
Date: 2011-3-12 20:41:24
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
  `id` bigint(11) NOT NULL auto_increment,
  `productName` varchar(50) default NULL,
  `dir_id` bigint(11) default NULL,
  `salePrice` double(10,2) default NULL,
  `supplier` varchar(50) default NULL,
  `brand` varchar(50) default NULL,
  `cutoff` double(2,2) default NULL,
  `costPrice` double(10,2) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `product` VALUES ('1', '罗技M90', '3', '90.00', '罗技', '罗技', '0.50', '35.00');
INSERT INTO `product` VALUES ('2', '罗技M100', '3', '49.00', '罗技', '罗技', '0.90', '33.00');
INSERT INTO `product` VALUES ('3', '罗技M115', '3', '99.00', '罗技', '罗技', '0.60', '38.00');
INSERT INTO `product` VALUES ('4', '罗技M125', '3', '80.00', '罗技', '罗技', '0.90', '39.00');
INSERT INTO `product` VALUES ('5', '罗技木星轨迹球', '3', '182.00', '罗技', '罗技', '0.80', '80.00');
INSERT INTO `product` VALUES ('6', '罗技火星轨迹球', '3', '349.00', '罗技', '罗技', '0.87', '290.00');
INSERT INTO `product` VALUES ('7', '罗技G9X', '3', '680.00', '罗技', '罗技', '0.70', '470.00');
INSERT INTO `product` VALUES ('8', '罗技M215', '2', '89.00', '罗技', '罗技', '0.79', '30.00');
INSERT INTO `product` VALUES ('9', '罗技M305', '2', '119.00', '罗技', '罗技', '0.82', '48.00');
INSERT INTO `product` VALUES ('10', '罗技M310', '2', '135.00', '罗技', '罗技', '0.92', '69.80');
INSERT INTO `product` VALUES ('11', '罗技M505', '2', '148.00', '罗技', '罗技', '0.92', '72.00');
INSERT INTO `product` VALUES ('12', '罗技M555', '2', '275.00', '罗技', '罗技', '0.88', '140.00');
INSERT INTO `product` VALUES ('13', '罗技M905', '2', '458.00', '罗技', '罗技', '0.88', '270.00');
INSERT INTO `product` VALUES ('14', '罗技MX1100', '2', '550.00', '罗技', '罗技', '0.76', '300.00');
INSERT INTO `product` VALUES ('15', '罗技M950', '2', '678.00', '罗技', '罗技', '0.78', '320.00');
INSERT INTO `product` VALUES ('16', '罗技MX Air', '2', '1299.00', '罗技', '罗技', '0.72', '400.00');
INSERT INTO `product` VALUES ('17', '罗技G1', '4', '155.00', '罗技', '罗技', '0.80', '49.00');
INSERT INTO `product` VALUES ('18', '罗技G3', '4', '229.00', '罗技', '罗技', '0.77', '96.00');
INSERT INTO `product` VALUES ('19', '罗技G500', '4', '399.00', '罗技', '罗技', '0.88', '130.00');
INSERT INTO `product` VALUES ('20', '罗技G700', '4', '699.00', '罗技', '罗技', '0.79', '278.00');

准备相应的domain

package com.cl.mybatis._01.damain;

public class Product {
    private Long id;
    private String productName;
    private Long dir_id;
    private Double  salePrice;
    private String supplier;
    private String brand;
    private Double cutoff;
    private Double costPrice;

    public Long getId() {
        return id;
    }

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

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public Long getDir_id() {
        return dir_id;
    }

    public void setDir_id(Long dir_id) {
        this.dir_id = dir_id;
    }

    public Double getSalePrice() {
        return salePrice;
    }

    public void setSalePrice(Double salePrice) {
        this.salePrice = salePrice;
    }

    public String getSupplier() {
        return supplier;
    }

    public void setSupplier(String supplier) {
        this.supplier = supplier;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getCutoff() {
        return cutoff;
    }

    public void setCutoff(Double cutoff) {
        this.cutoff = cutoff;
    }

    public Double getCostPrice() {
        return costPrice;
    }

    public void setCostPrice(Double costPrice) {
        this.costPrice = costPrice;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", productName='" + productName + '\'' +
                ", dir_id=" + dir_id +
                ", salePrice=" + salePrice +
                ", supplier='" + supplier + '\'' +
                ", brand='" + brand + '\'' +
                ", cutoff=" + cutoff +
                ", costPrice=" + costPrice +
                '}';
    }
}

准备dao

dao接口

package com.cl.mybatis._01.dao;

import com.cl.mybatis._01.damain.Product;

import java.io.IOException;
import java.util.List;

public interface IProductDao {
    void save(Product product);

    void update(Product product);

    void delete(Long id);

    Product findById(Long id) throws Exception;

    List<Product> findAll() throws Exception;
}

抽取工具类

package com.cl.mybatis._01.util;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //读取配置文件,以输入流的形式
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //创建全局的sqlSessionFactory,随Tomcat的启动创建,随Tomcat的关闭而销毁
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("解析xml失败");
        }
    }

    /**
     * 创建session对象
     * @return
     */
    public static SqlSession openSession() throws Exception {
        if(sqlSessionFactory == null){
            throw new Exception("解析xml异常。。。");
        }
        return sqlSessionFactory.openSession();
    }

}

dao实现

package com.cl.mybatis._01.dao.impl;

import com.cl.mybatis._01.damain.Product;
import com.cl.mybatis._01.dao.IProductDao;
import com.cl.mybatis._01.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

public class ProductDaoImpl implements IProductDao {
    @Override
    public void save(Product product) {
        SqlSession sqlSession = null;
        try {
            //获取sqlSession对象,每个线程一个,不可共享
            sqlSession = MybatisUtils.openSession();
            //对应xml里的sql  id
            String statement = "com.cl.mybatis._01.dao.IProductDao.save";
            //执行插入
            sqlSession.insert(statement, product);
            //提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Product product) {
        SqlSession sqlSession = null;
        try {
            //获取sqlSession对象,每个线程一个,不可共享
            sqlSession = MybatisUtils.openSession();
            //对应xml里的sql  id
            String statement = "com.cl.mybatis._01.dao.IProductDao.update";
            //执行插入
            sqlSession.update(statement, product);
            //提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Long id) {
        SqlSession sqlSession = null;
        try {
            //获取sqlSession对象,每个线程一个,不可共享
            sqlSession = MybatisUtils.openSession();
            //对应xml里的sql  id
            String statement = "com.cl.mybatis._01.dao.IProductDao.delete";
            //执行插入
            sqlSession.delete(statement, id);
            //提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Product findById(Long id) throws Exception {
        //获取sqlSession对象,每个线程一个,不可共享
        SqlSession sqlSession = MybatisUtils.openSession();
        //对应xml里的sql  id
        String statement = "com.cl.mybatis._01.dao.IProductDao.findById";
        //执行插入
        Product product = sqlSession.selectOne(statement,id);
        return product;
    }

    @Override
    public List<Product> findAll() throws Exception {
        //获取sqlSession对象,每个线程一个,不可共享
        SqlSession sqlSession = MybatisUtils.openSession();
        //对应xml里的sql  id
        String statement = "com.cl.mybatis._01.dao.IProductDao.findAll";
        //执行插入
        List<Product> products = sqlSession.selectList(statement);
        return products;
    }
}

ProductDaoImpl .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">
<!--namespace:映射命名空间    一般都是写dao接口的全限定名-->
<mapper namespace="com.cl.mybatis._01.dao.IProductDao">
    <!--
    id:给查询sql语句取一个别名(必须独一无二)
    resultType:返回的结果值类型
    -->
    <select id="findAll" resultType="com.cl.mybatis._01.damain.Product">
        SELECT * FROM product
    </select>

    <!--parameterType:参数类型-->
    <select id="findById" resultType="com.cl.mybatis._01.damain.Product">
        SELECT * FROM product WHERE id = #{id}
    </select>

    <delete id="delete" parameterType="long">
        DELETE FROM product WHERE id = #{id}
    </delete>

    <insert id="save" parameterType="com.cl.mybatis._01.damain.Product">
        INSERT INTO product(productName, dir_id, salePrice, supplier, brand, cutoff, costPrice)
        VALUES (#{productName},#{dir_id},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
    </insert>

    <update id="update" parameterType="com.cl.mybatis._01.damain.Product">
        UPDATE product SET productName=#{productName}, dir_id=#{dir_id}, salePrice=#{salePrice}, supplier=#{supplier}, brand=#{brand}, cutoff=#{cutoff}, costPrice=#{costPrice} WHERE id=#{id}
    </update>


</mapper>

测试类

package com.cl.mybatis._01.test;

import com.cl.mybatis._01.damain.Product;
import com.cl.mybatis._01.dao.IProductDao;
import com.cl.mybatis._01.dao.impl.ProductDaoImpl;

import java.util.List;

public class IProductDaoTest {

    private IProductDao productDao = new ProductDaoImpl();
    @org.junit.Test
    public void save() throws Exception {
        Product product = new Product();
        product.setBrand("七匹狼男装");
        product.setCostPrice(22.3);
//        product.setDir_id(1L);
        product.setProductName("男装");
        product.setSupplier("赵日天");
        product.setCutoff(0.99);
        product.setSalePrice(10.21);
        productDao.save(product);
    }

    @org.junit.Test
    public void update() {
        Product product = new Product();
        product.setBrand("七匹狼男装");
        product.setCostPrice(22.3);
        product.setId(1L);
        product.setProductName("男装");
        product.setSupplier("赵日天");
        product.setCutoff(0.99);
        product.setSalePrice(10.21);
        productDao.update(product);
    }

    @org.junit.Test
    public void delete() {
        productDao.delete(22L);
    }

    @org.junit.Test
    public void selectById() {
        try {
            System.out.println(productDao.findById(5L));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @org.junit.Test
    public void selectAll() {
        try {
            List<Product> products = productDao.findAll();
            products.forEach(p->{
                System.out.println(p);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

mybatis高级查询

准备数据库表

/*
SQLyog Ultimate v12.08 (64 bit)
MySQL - 5.5.49 : Database - mybatis
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `employee` */

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` bit(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8;

/*Data for the table `employee` */

insert  into `employee`(`id`,`name`,`age`,`sex`) values (1,'云上城0',0,''),(2,'云上城1',1,'\0'),(3,'云上城2',2,''),(4,'云上城3',3,'\0'),(5,'云上城4',4,''),(6,'云上城5',5,'\0'),(7,'云上城6',6,''),(8,'云上城7',7,'\0'),(9,'云上城8',8,''),(10,'云上城9',9,'\0'),(11,'云上城10',10,''),(12,'云上城11',11,'\0'),(13,'云上城12',12,''),(14,'云上城13',13,'\0'),(15,'云上城14',14,''),(16,'云上城15',15,'\0'),(17,'云上城16',16,''),(18,'云上城17',17,'\0'),(19,'云上城18',18,''),(20,'云上城19',19,'\0'),(21,'云上城20',20,''),(22,'云上城21',21,'\0'),(23,'云上城22',22,''),(24,'云上城23',23,'\0'),(25,'云上城24',24,''),(26,'云上城25',25,'\0'),(27,'云上城26',26,''),(28,'云上城27',27,'\0'),(29,'云上城28',28,''),(30,'云上城29',29,'\0'),(31,'云上城30',30,''),(32,'云上城31',31,'\0'),(33,'云上城32',32,''),(34,'云上城33',33,'\0'),(35,'云上城34',34,''),(36,'云上城35',35,'\0'),(37,'云上城36',36,''),(38,'云上城37',37,'\0'),(39,'云上城38',38,''),(40,'云上城39',39,'\0'),(41,'云上城40',40,''),(42,'云上城41',41,'\0'),(43,'云上城42',42,''),(44,'云上城43',43,'\0'),(45,'云上城44',44,''),(46,'云上城45',45,'\0'),(47,'云上城46',46,''),(48,'云上城47',47,'\0'),(52,'云上城56',25,''),(53,'张三丰',22,''),(54,'西门吹雪',23,'\0');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

query查询条件

package com.cl.mybatis._02_mapper.query;

public class EmployeeQuery {
    private String name;
    private Integer minAge;
    private Integer maxAge;
    private Boolean sex;

    public String getName() {
        return name;
    }

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

    public Integer getMinAge() {
        return minAge;
    }

    public void setMinAge(Integer minAge) {
        this.minAge = minAge;
    }

    public Integer getMaxAge() {
        return maxAge;
    }

    public void setMaxAge(Integer maxAge) {
        this.maxAge = maxAge;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }
}

domain

package com.cl.mybatis._02_mapper.damain;

public class Employee {
    private Long id;
    private String name;
    private Integer age;
    private Boolean sex;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Enployee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}

准备mapper

接口

package com.cl.mybatis._02_mapper.mapper;

import com.cl.mybatis._02_mapper.damain.Employee;
import com.cl.mybatis._02_mapper.query.EmployeeQuery;

import java.util.List;

public interface EmployeeMapper {
    void save(Employee product);

    void batchSave(List list);

    void batchDelete(Long[] ids);

    List<Employee> findByQuery(EmployeeQuery query);

    List<Employee> findAll();
}

准备EmployeeMapper .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">
<!--namespace:映射命名空间    一般都是写dao接口的全限定名-->
<mapper namespace="com.cl.mybatis._02_mapper.mapper.EmployeeMapper">
<!--抽取公共的sql语句,可抽的地方:
	1.where后面的语句
	2.数据库字段列名
	使用<include refid="cloumnSql"/> 调用
-->
    <sql id="querySql">
        <where>
            <if test="name!=null and name!=''">
                AND name like '%${name}%'
            </if>
            <if test="maxAge!=null">
                <![CDATA[AND age<=#{maxAge}]]>
            </if>
            <if test="minAge!=null">
                <![CDATA[AND age>=#{minAge}]]>
            </if>
            <if test="sex!=null">
                AND sex = #{sex}
            </if>
        </where>
    </sql>

    <sql id="cloumnSql">
        id,name,age,sex
    </sql>
    <!--
    id:给查询sql语句取一个别名(必须独一无二)
    resultType:返回的结果值类型
    -->
    <select id="findAll" resultType="Employee">
        SELECT
        <include refid="cloumnSql"/>
        FROM employee
    </select>
    <select id="findByQuery" resultType="Employee" parameterType="EmployeeQuery">
        SELECT
        <include refid="cloumnSql"/>
        FROM employee
        <include refid="querySql"/>
    </select>

    <insert id="save" parameterType="Employee" useGeneratedKeys="true"
            keyColumn="id" keyProperty="id">
        INSERT INTO employee(<include refid="cloumnSql"/>)
        VALUES (null,#{name},#{age},#{sex})
    </insert>

    <delete id="batchDelete">
        DELETE FROM employee WHERE id IN
        <foreach collection="array" open="(" close=")" item="item" separator=",">
            #{item}
        </foreach>
    </delete>


    <insert id="batchSave">
        INSERT INTO employee(
        <include refid="cloumnSql"/>
        )VALUES
        <foreach collection="list" item="item" separator=",">
            (null,#{item.name},#{item.age},#{item.sex})
        </foreach>
    </insert>
</mapper>

mybatis-configxml

<configuration>
...
<!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <mapper resource="com/cl/mybatis/_01/dao/impl/ProductDaoImpl.xml"/>
        <mapper resource="com/cl/mybatis/_02_mapper/mapper/EmployeeMapper.xml"/>
    </mappers>
<!--配置全限定名对应的别名,这样在设置resulttype的时候就可以使用别名-->
    <typeAliases>
        <typeAlias type="com.cl.mybatis._02_mapper.damain.Employee" alias="Employee"></typeAlias>
        <typeAlias type="com.cl.mybatis._02_mapper.query.EmployeeQuery" alias="EmployeeQuery"></typeAlias>
    </typeAliases>
</configuration>

测试

package com.cl.mybatis._02_mapper.test;

import com.cl.mybatis._01.util.MybatisUtils;
import com.cl.mybatis._02_mapper.damain.Employee;
import com.cl.mybatis._02_mapper.mapper.EmployeeMapper;
import com.cl.mybatis._02_mapper.query.EmployeeQuery;
import org.apache.ibatis.session.SqlSession;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import static org.junit.Assert.*;

public class EmployeeMapperTest {
    @Test
    public void save() throws Exception {
        SqlSession sqlSession = MybatisUtils.openSession();
        //获取映射器
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = new Employee();
        employee.setAge(25);
        employee.setName("云上城" + 56);
        employee.setSex(true);
        employeeMapper.save(employee);
        sqlSession.commit();
        System.out.println(employee);
    }

    @Test
    public void update() {
    }
//批量删除,数组或者集合
    @Test
    public void batchDelete() {
        Long[] ids = {49L,50L,51L};
        try {
            //获取sqlsession
            SqlSession sqlSession = MybatisUtils.openSession();
            //获取映射器
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            employeeMapper.batchDelete(ids);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//批处理,批量添加
    @Test
    public void batchSave() throws Exception {
        Employee e1 = new Employee();
        e1.setName("张三丰");
        e1.setAge(22);
        e1.setSex(true);
        Employee e2 = new Employee();
        e2.setName("西门吹雪");
        e2.setAge(23);
        e2.setSex(false);
        List<Employee> employees = new ArrayList<>();
        employees.add(e1);
        employees.add(e2);


        SqlSession sqlSession = MybatisUtils.openSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.batchSave(employees);
        sqlSession.commit();
    }
//查询所有
    @Test
    public void findAll() {
        try {
            //获取sqlsession
            SqlSession sqlSession = MybatisUtils.openSession();
            //获取映射器
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            List<Employee> list = employeeMapper.findAll();
            list.forEach(e -> {
                System.out.println(e);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
//根据查询添加查询,查询条件为空查全部
    @Test
    public void findByQuery() {
        EmployeeQuery employeeQuery = new EmployeeQuery();
        employeeQuery.setMaxAge(30);
        employeeQuery.setMinAge(18);
        employeeQuery.setName("2");
        employeeQuery.setSex(true);
        try {
            //获取sqlsession
            SqlSession sqlSession = MybatisUtils.openSession();
            //获取映射器
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            List<Employee> list = employeeMapper.findByQuery(employeeQuery);
            list.forEach(e -> {
                System.out.println(e);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第一次写博客,那是因为我想与大家分享.Net世界.我原来是ASP程序员,与.Net结缘那是在两年多前.第一次接触它,就喜欢上了.哈哈 接着我给大家分享一下我在项目中用到的数据访问层,这个是我用微软网站上得到的DBHepler数据库访问层的一次改编,让它支持实体类和用表达 式的方式生成SQL,而且更关键的是,他是采用参数的方式传值的,这样就避免了SQL的注入啦.. 以下是这个项目的结构 [SuperDAL] ---DbHelper.cs(来自MSDN的数据访问层) ---EntityManager.cs(实体类管理) ---Expressions.cs(实体类表达式查询) ---Expression.cs(实体类表达式) ---OrderByExpressions.cs(排序表达式查询) ---OrderByExpression.cs(排序表达式) ---ObjectValues -------OrderBy.cs(排序枚举类) ---DBManager.cs(数据访问类管理) ---DbParams.cs(数据库访问类参数) ---DataTableExtensions.cs(这个就是顾名思义啦,DataTable传实体类) 在这里最主要介绍的就是EntityManager这个啦,使用方法如下: 有数据库DB的一张表Customs CREATE TABLE [Customs] ( [Name] [varchar] (20) , [Password] [varchar] (20) , [Email] [varchar] (50) , [Phone] [varchar] (11) NULL , [Old] [int] , [Birthday] [DateTime] ) 有个实体类Customs.cs,结构如下: public class Customs { public string Name {get;set;} public string Password {get;set;} public string Email {get;set;} public string Phone {get;set;} public int Old{get;set} public DateTime Brithday {get;set;} } 数据库表与实体Customs结构是一一对应的.有了实体类CUstoms,下面就可以操作实体类跟操作数据库一样的啦,我们新建一个实体类管理类 CustomsManager.cs public class CustomsManager:EntityManager { public Customs GetByName(string name) { //创建表达式Expressions Expressions exps=new Expressions(); //向表达式添加条件 exps.Eq("name",name); //根据条件查询返回实体类 return EM_GetUnique(exps); } public List SearchByName(string name) { //同样像上面一样建立表达式类 Expressions exps=new Expressions(); exps.Like("name",name);//当然,有年朋友会说如果我要姓为"陈"的,那有些人的名字带陈的怎么办,没关系,可以改为 exps.LeftLike ("name",name); //根据条件查询返回实体类 return EM_GetEntity(exps); } /// /// 登录 /// /// 用户名 /// 密码 public List Login(string name,string password) { Expressions exps=new Expressions(); exps.Eq("name",name); exps.Eq("password",password); return EM_GetEntity(exps); } /// /// 选择年龄大于指定岁数的,并按年龄从小到大排序 /// /// 年龄 public List SelectOlder(int old) { Expressions exps=new Expressions(); exps.Gt("old",old); exp.OrderBys.Add("old", OrderBy.Asc); return EM_GetEntity(exps); } /// /// 选择年龄大于小于指定岁数段的,并按年龄从小到大,姓名从字母升序排序 /// /// 年龄 public List SelectByOld(int oldStart,int oldend) { Expressions exps=new Expressions(); exps.Between("old",oldStart,oldEnd); exp.OrderBys.Add("old", OrderBy.Asc); exp.OrderBys.Add("name",OrderBy.Asc); return EM_GetEntity(exps); } #region 增删改 操作 /// /// 更新操作 /// /// 实体类 public int Update(Customs customs) { return EM_Save(customs);//返回更新的记录数,当然,一般成功执行就会返回1;也可以改上面为public void Update(Customs customs) } /// /// 删除操作 /// /// public int DeleteByName(string name) { Expressions exps=new Expressions(); exps.Eq("name",name); return EM_Delete(exps); } /// /// 删除操作 /// /// 实体类 public int Save(Customs custom) { return EM_Save(custom); } #endregion } 当然还有更多的也就不一一贴出来了 Expressions支持的表达式有 1. Eq (等于)[name=value] 2. NotEq (不等于)[not name = value] 3. Ge (大于等于)[name >=value] 4. Gt (大于)[name>value] 5. Le (小于等于)[name<=value] 6. Lt (小于)[name<value] 7. In (包括)[name in (value)] 8. NotIn (不包括)[not name in (value) 9. IsNotNull (不为NULL)[not name is null] 10. IsNull (等于NULL)[name is null] 11. Between (之间)[name between valueStart and valueEnd] 12. Like (模糊) [name like ‘%value%’ ] 13. LeftLike (左模糊) [name like ‘%value’] 14. RightLike (右模糊) [name like ‘value%’] 其它功能待与Net爱好者探讨啦,希望你有更好的思路
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值