Mybatis的理解与CRUD基本使用

MyBatis是什么

MyBatis是一个ORM的数据库持久化框架

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

Mybatis的原理

以一定的映射方式,把实体模型和数据库关系的映射
使用简单的 XML或注解用于配置和原始映射,将接口和普通的 Java对象,映射成数据库中的记录

导入jar包

实现

1.第一步要获取SqlSessionFactory
2.需要准备一个核心的Mybatis-config.xml文件
3.拿到SqlSessionFactory之前需要读取核心的xml配置文件
4.需要构造者(SqlSessionFactoryBuilder)来创建它
5.映射文件准备
6.通过SqlSessionFactory获取SqlSession执行映射SQL

配置jdbc.propettise

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

配置mybatis-config.xml

连接数据库

<!--导入-->
    <properties  resource="jdbc.properties" />

连接数据库用户名,密码,数据库表以及驱动

<environments default="development">


        <environment id="development">
        事务管理
            <transactionManager type="JDBC"/>
            <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>

配置别名,在实例对象映射xml中空间匿名和resultType可简写,不需要写对象全限定类名

 <!-- 别名-->
    <typeAliases>
       <!-- <typeAlias type="cn.itsource.model.Product" alias="Product"></typeAlias>-->
        <package name="cn.itsource.model" ></package>
        <package name="cn.itsource.vo" ></package>
    </typeAliases>

mappers代表的是相应的ORM映射文件

<mappers>
        <mapper resource="cn/itsource/model/ProductMapper.xml"/>
    </mappers>

准备一个对象提供get set toString

public class Product {
        private Long id;
        //商品名称
        private String productName;
        //商品分类编号
        private  Long dir_id;

        private BigDecimal salePrice;
        //供应商
        private String supplier;
        //品牌
        private String brand;
        //折扣价
        private Double cutoff;
        //进价
        private BigDecimal costPrice;

在对象下面添加一个映射配置文件,SSM整合之后有个mapper专门放配置文件

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
	这个Mapper的主要功能就是写sql
	mapper:根
    namespace的值,规则的:映射文件XxxMapper.xml所在的包+domain类名+Mapper
 -->
<mapper namespace="Product">
   
    <!--
        select : 这里面写查询语句
        id:用来确定这条sql语句的唯一以后我们确定唯一,也就是找sql语句 : namespace +.+ id
        parameterType : 传入的参数类型  long:大Long  _long:long 
        resultType : 对象全限定类名
     -->
	根据id查询
    <select id="selectOne" parameterType="long" resultType="cn.itsource.model.Product">
		select * from product where id=#{id}
	</select>
   
   	查询全部
    <select id="selectAll" resultType="cn.itsource.model.Product">
        select *from product
    </select>
    

</mapper>

namespace :映射文件XxxMapper.xml所在的包+domain类名+Mapper
select : 这里面写查询语句
id:在后台调用crud方法的时候需要传namespace.id
parameterType : 传入的参数类型 long:大Long _long:小long,通过id查询或者删除就用long
resultType : 对象全限定类名

创建一个测试类

通过id查询一条数据

 <select id="selectOne" parameterType="long" resultType="cn.itsource.model.Product">
		select * from product where id=#{id}
	</select>
public class ProductTest {
    @Test
        public void testSelectOne()throws Exception{
            //读取配置
            String resource="mybatis-config.xml";
            //创建sqlSessionFactory
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            //获取sqlsession操作
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //调用namespace.id+参数
            Product selectOne = sqlSession.selectOne("Product.selectOne", 3L);
            //打印结果
            //查询第三条数据
            //Product{id=3, productName='罗技M115', dir_id=3, salePrice=99.00, supplier='罗技', brand='罗技', cutoff=0.6, costPrice=38.00}
            System.out.println(selectOne);

查询全部

<select id="selectAll" resultType="cn.itsource.model.Product">
        select *from product
    </select>
 public void testSelectAll()throws Exception{
            //获取配置文件
            String resource="mybatis-config.xml";
            //创建sqlSessionFactory
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            //获取sqlSession操作
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //查询所有集合 传入空间匿名.id  查询全部不需要传参
            List<Product> list = sqlSession.selectList("Product.selectAll");
            //打印所有数据
            list.forEach(item-> System.out.println(item));
        }

添加
parameterType:需要传入我们的对象
useGeneratedKeys: 是否需要主键
keyColumn:主键所在的列
keyProperty:对象中的属性(代表主键的那个属性)

<insert id="save" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="cn.itsource.model.Product">
      insert into product (<include refid="insertFiled" />)
      values (
        #{productName},
        #{dir_id},
        #{salePrice},
        #{supplier},
        #{brand},
        #{cutoff},
        #{costPrice}
        )
    </insert>
//添加
       @Test
            public void testSave()throws Exception{
            //读取配置
            String resource="mybatis-config.xml";
            //创建sqlSessionFactory
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            //获取sqlsession操作
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Product product=new Product();
            //在数据库添加一条数据
            product.setProductName("罗技专属冯皇001");
            //匿名空间.id,传参
            sqlSession.insert("Product.save", product);
            sqlSession.commit();

批量删除
!collection=“list”:传入的list,相当于map的key,通过list得到传入的整个集合的值;
index=“index” :每次循环的索引
item=“id” :每次循环的这个值
open="(" :以什么开始
separator=",":分隔符
close=")":以什么结束


<delete id="batchDelete" parameterType="list">
        delete from product where id in

        <foreach collection="list" item="item" separator="," open="(" close=")" index="index">
            #{item}
        </foreach>
    </delete>
 //批量删除
        @Test
            public void testbatchDelete()throws Exception{
            SqlSession sqlSession=null;
            try {
                 sqlSession = MybatisUtils.getSession();
                //创建个集合,选择要批量删除的数据
                List<Integer> list = Arrays.asList(22, 23, 24);
                //删除方法
                sqlSession.delete("Product.batchDelete",list);
                //提交事务
                sqlSession.commit();

修改数据

<update id="update" parameterType="Product">
        update product
        <set>
            <if test="productName!=null and productName!=''">
                productName =#{productName},
            </if>
            <if test="dir_id!=null">
                dir_id =#{dir_id},
            </if>
            <if test="salePrice!=null">
                salePrice =#{salePrice},
            </if>
            <if test="supplier!=null">
                supplier=#{supplier},
            </if>
            <if test="brand!=null and productName!=''">
                brand=#{brand},
            </if>

            <if test="cutoff!=null">
                cutoff=#{cutoff},
            </if>
            <if test="costPrice!=null">
                costPrice=#{costPrice}
            </if>
        </set>
        where id=#{id}
    </update>

set,去逗号,where,去and

@Test
            public void testupdate()throws Exception{
            SqlSession sqlSession=null;
            try {
                 sqlSession = MybatisUtils.getSession();
                 Product product=new Product();
                 product.setProductName("冯舔的黄金鼠标");
                 product.setId(20L);
                 sqlSession.update("Product.update",product);
                 sqlSession.commit();

批量添加

**<insert id="batchSave" parameterType="list">
        insert into product (
        <include refid="insertFiled" />
        )
        values
        <foreach collection="list" item="item" separator=",">
            (
            #{item.productName},
            #{item.dir_id},
            #{item.salePrice},
            #{item.supplier},
            #{item.brand},
            #{item.cutoff},
            #{item.costPrice}

            )
        </foreach>
    </insert>**
 //批量增加
        @Test
            public void testbatchSave()throws Exception{
            SqlSession sqlSession=null;
            try {
                 sqlSession = MybatisUtils.getSession();
                 //创建集合,批量增加
                List<Product> list=new ArrayList();
                //批量增加五条数据
                for (int i = 0; i < 5; i++) {
                    Product product=new Product();
                    product.setProductName(i+"NIKE");
                    list.add(product);
                }
                //执行批量添加方法
                sqlSession.insert("Product.batchSave",list);
                //提交事务
                sqlSession.commit();

MyBatis运行日志

配置文件(log4j.properties)
我们需要把日志打印出来,帮助我们进行分析与排错

log4j.rootLogger=debug, stdout
#log4j.rootLogger=NONE
log4j.logger.cn.itsource=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

{}和${}区别

#{}:表示一个占位符号,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入
美元符{}: $将传入的参数直接显示生成在sql中,被当成一个对象0
所以尽量用#{}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值