Mybatis完整功能实现CRUD

1 篇文章 0 订阅

Mybatis完整功能实现CRUD

对于刚使用的新手提供了完整的增删改查并附带测试,首先我们介绍下ORM

对象关系映射的框架

1.对象:java domain对象 比如User Person Animal new User
2.映射:数据表 一行记录
3.关系:表和表之间的关系 就是对象和对象关系

在这里插入图片描述

(3)JDBC有优缺点

编写比较麻烦
重复性太高
很多sql都需要写到代码,sql和代码耦合度比较高
queryAll 封装操作
没有性能控制 --缓存

优点:操作数据库最底层
自己可以灵活操作sql

(4)JPA的优缺点

你怎么懂的Sql 都可以操作数据库,JPA提供缓存控制(ehcache)
有些性能不好控制,比如find 默认查询所有列

(5)MyBatis学习

Mybatis就是ORM一种实现的框架
MyBatis完成持久层框架

可以灵活的操作sql
有缓存支持
不用封装数据,避免jdbc重复性代码

Struts2SpringHibernate – SSH
SpringMVCSpringSpringJdbc
SpringMVCSpringSpringDataJPA
SpringMVCSpringMyBatis --目前而言比较流行结构
SpringBoot SpringCloud SpringMVC Spring MyBatis

(5)MyBatis第一个入门程序

a.导入相应jar包到项目
以前导包方式
b.配置 MyBatis-Config.xml
配置环境 (连接数据库四大配置dirver url username password)
配置Mapper文件–主要写Sql文件(insert update delete select)
在主MyBatis-Config.xml里面去引用Mapper

c.写个测试类测试代码
SqlSessionFactoryBuilder- SqlSessionFactory–SqlSession

(5)使用MyBatis完成CRUD

新增 – insert
修改-- update
删除 --delete
查询一条 --selectOne
查询所有–selectAll

工具类抽取MyBatisUtils

(6)使用注意事项:

A错误:
Error querying database. Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for cn.itsource._01_hello.ProductMapper.getOne

情况一:主的配置文件里面 没有去引用mapper
情况二:还有配置文件 方法写错

错误:

The error may exist in cn.itsource._01_hello/ProductMapper.xml

正确写法:

类的全限定名不要写错

CRUD

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

这是Domain层

//这是Domain层

package cn.itsource.domain;

public class Product {
    private Long id;
    //商品名称
    private String productName;
    //品牌
    private String brand;
    //供应商
    private String supplier;
    //零售价
    private Double salePrice;
    //进价
    private Double costPrice;
    //折扣比例
    private Double cutoff;
    //商品分类编号
    private Long dir_id;

    //提供getter与setter...

    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 String getBrand() {
        return brand;
    }

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

    public String getSupplier() {
        return supplier;
    }

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

    public Double getSalePrice() {
        return salePrice;
    }

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

    public Double getCostPrice() {
        return costPrice;
    }

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

    public Double getCutoff() {
        return cutoff;
    }

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

    public Long getDir_id() {
        return dir_id;
    }

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

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

dao层



//dao层



package cn.itsource.dao;

import cn.itsource.domain.Product;

import java.util.List;

public interface IProductDao {
    /**
     * 添加一个商品
     */
    void save(Product p);

    /**
     * 更新一个商品
     */
    void update(Product p);

    /**
     * 删除一个商品
     */
    void delete(Long id);

    /**
     * 得到一个商品
     */
    Product getOne(Long id);
    /**
     * 得到所有商品
     */
    List<Product> getAll();

}

实现类

package cn.itsource.dao.impl;

import cn.itsource.dao.IProductDao;
import cn.itsource.domain.Product;
import cn.itsource.util.ProductUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ProductDaoimpl implements IProductDao {
    public static String NAME_SPACE = "cn.itsource.ProductMapper.";
    @Override
    public void save(Product product) {
        SqlSession session = ProductUtil.getSession();
        session.insert("save", product);
        session.commit();
        session.close();
    }

    @Override
    public void update(Product product) {
        SqlSession session = ProductUtil.getSession();
        session.update("update",product);
        session.commit();
        session.close();
    }

    @Override
    public void delete(Long id) {
        SqlSession session = ProductUtil.getSession();
        session.delete("delete",id);
        session.commit();
        session.close();
    }

    @Override
    public Product getOne(Long id) {
        SqlSession session = ProductUtil.getSession();
        Product product = (Product)session.selectOne("getOne", id);
        session.close();
        return product;
    }

    @Override
    public List<Product> getAll() {
        SqlSession session = ProductUtil.getSession();
        List<Product> products = session.selectList(NAME_SPACE + "getAll");
        session.close();
        return products;
    }
}

工具类


package cn.itsource.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.Reader;

public class ProductUtil {
    // 保证SqlSessionFactory是单例
    private static SqlSessionFactory sqlSessionFactory;

    // SqlSessionFactory类似于JPA的EntityManagerFactory,Hibernate的SessionFactory
    // SqlSession 类似于JPA的EntityManager,Hibernate的Session

    static {
        try {
            Reader reader = Resources.getResourceAsReader("MyBatis-Config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析MyBatis的配置文件或者映射文件出现异常:" + e.getMessage());
        }
    }

    // 对外提供一个类
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }

}

测试类

package cn.itsource.test;

import cn.itsource.dao.IProductDao;
import cn.itsource.dao.impl.ProductDaoimpl;
import cn.itsource.domain.Product;
import org.junit.Test;

import java.util.List;

public class Tset {
    IProductDao productDao = new ProductDaoimpl();
    @Test
    public void testgetAll(){
        List<Product> list = productDao.getAll();
        for (Product product : list) {
            System.out.println(product);
        }

    }
    @Test
    public void testgetOne(){
        Product product = productDao.getOne(1L);
        System.out.println(product);
    }
    @Test
    public void testSave(){
        Product product = new Product();
        product.setProductName("sfddfdsaf");
        productDao.save(product);
    }
    @Test
    public void testUpdate(){
        Product product = productDao.getOne(21L);
        product.setProductName("1111111");
        productDao.update(product);
    }
    @Test
    public void testDelete(){
        productDao.delete(21L);
        Product product = productDao.getOne(21L);
        System.out.println(product);
    }
}

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的主要功能就是写sql
	mapper:根
	namespace:命令空间 (用来确定唯一) 以前这个是可以不加的,现在必需加
     namespace的值,规则的:映射文件XxxMapper.xml所在的包+domain类名+Mapper
 -->
<mapper namespace="cn.itsource.ProductMapper">
    <!--
        select : 这里面写查询语句
        id:用来确定这条sql语句的唯一
               以后我们确定唯一,也就是找sql语句 : namespace +.+ id
             例: cn.itsource.mybatis.day1._1_hello.ProductMapper.get
        parameterType : 传入的参数类型  long:大Long  _long:小long (具体的对应请参见文档)
        resultType : 结果类型(第一条数据返回的对象类型) 自己的对象一定是全限定类名
     -->
    <select id="getOne" parameterType="long" resultType="cn.itsource.domain.Product">
        select * from product where id = #{id}
    </select>
    <select id="getAll"  resultType="cn.itsource.domain.Product">
        select * from product
    </select>
    <select id="save"  resultType="cn.itsource.domain.Product">
        <!-- #{productName}==product.getProductName() -->
        insert into product(productName,salePrice,costPrice,cutoff,supplier,brand,dir_id)
        values
        (#{productName},#{salePrice},#{costPrice},#{cutoff},#{supplier},#{brand},#{dir_id})

    </select>
    <select id="update"  resultType="cn.itsource.domain.Product">
        <!-- #{productName}==product.getProductName() -->
        update product set productName=#{productName},salePrice=#{salePrice},costPrice=#{costPrice},
        cutoff=#{cutoff},supplier=#{supplier},brand=#{brand},dir_id=#{dir_id}
        where id=#{id}

    </select>

    <select id="delete" parameterType="long"  resultType="cn.itsource.domain.Product">
       	delete from product where id=#{id}
    </select>

</mapper>



Mybtatis-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文件 -->
    <properties resource="db.properties"></properties>
    <!-- 将一个包下面的所有类都取上别名:<package name="cn.itsource.domain" /> -->
    <!-- alias:取的别名 -->
    <!-- type:这个别名所对应的Java类 :别名使用的时候与大小写无关 -->
    <typeAliases>
        <!-- 练习的时候使用 -->
        <!--<typeAlias type="cn.itsource.domain.Product" alias="Product" />-->
        <!-- 做项目的时候使用 -->
         <package name="cn.itsource.domain.Product" />
    </typeAliases>

    <!-- default:默认使用哪一个环境(必需对应一个环境的id) -->
    <environments default="development">
        <!-- 一个环境 id:为这个环境取唯一一个id名称 -->
        <environment id="development">
            <!-- 事务管理 type:JDBC(支持事务)/MANAGED(什么都不做) -->
            <transactionManager type="JDBC" />
            <!-- 数据源, 连接池 type(POOLED):MyBatis自带的连接池 -->
            <dataSource type="POOLED">
                <!-- 连接数据库的参数 -->
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 添加映射文件的位置 -->
    <mappers>
        <!-- 添加映射文件:1.前面不添加/,表示相对路径;2.使用的文件路径/,不是包路径. -->
        <!-- 单表crud -->
        <!-- <mapper resource="cn/itsource/mybatis/a_hello/ProductMapper.xml" /> -->
        <!-- 单向多对一 -->
        <mapper resource="cn/itsource/ProductMapper.xml" />
    </mappers>
</configuration>

数据库连接

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///mybatis
db.username=root
db.password=123456

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值