MyBatis(上)

目录

1、概述:

2、MyBatis的配置:

1、第一个是: mybatis-config.xml:

1、environments:

2、transactionManager:

3、dataSource:

2、第二个是:XXXMpaper.xml

3、MyBatis完成CRUD:

1、Create(增):

2、delete(删):

3、update(改)

4、select(查): 

4、MyBatis的参数处理:

1、单个简单参数:

2、Map参数:

3、对象类型:

 4、多参数:

5、多参数之Param注解

6、 返回map集合:

(1)单个map:

(2)多个map:

(3)返回Map:,map>

7、resultMap结果映射:

(1)resultMap进行结果映射

(2)开启驼峰命名自动映射:


1、概述:

        MyBatis(以前称为iBATIS)是一个Java持久性框架,用于简化数据库访问和与关系数据库的交互。它提供了一种将数据库操作与Java应用程序的业务逻辑分离的方式,使开发人员能够更轻松地编写数据库访问代码。MyBatis本质上就是对JDBC的封装,通过MyBatis完成CRUD。

        MyBatis作为持久层的一个框架,使用到的一个思想就是ORM,用于将对象模型(通常是面向对象编程语言中的类和对象)映射到关系数据库中的数据模型(表、列等)。ORM框架允许开发人员以面向对象的方式进行数据库操作,而不必直接编写SQL查询。通过这个可以使Java中的对象转化为数据库表的一个记录,这种转化的关系就叫做映射。

        之前也注意到啦,什么domain、bean、pojo,只不过一开始没注意其中的含义,大概意思就是,pojo是普通的java类,bean(Spring框架的时候使用的比较多),domain(领域模型------封装数据的),不同的开发的团队可能叫法不一样。

        MyBatis是一个半自动化的ORM框架,就是需要我们手动去书写SQL语句,Hibernate是一个全自动的ORM框架。

  1. SQL映射:MyBatis通过XML或注解方式定义SQL查询,将Java对象与数据库表之间的映射关系。这使得开发人员可以在SQL中编写原生SQL查询,而不需要使用对象关系映射(ORM)框架。

  2. 简化数据访问:MyBatis处理了许多数据库访问的底层细节,如连接管理、事务处理和结果集映射,从而使开发人员能够专注于业务逻辑而不必关心这些细节。

  3. 动态SQL:MyBatis允许在SQL查询中使用动态SQL,根据条件动态生成SQL查询,这在构建复杂查询时非常有用。

  4. 参数映射:MyBatis支持将Java对象作为参数传递给SQL查询,参数映射工作非常灵活,可以轻松地传递单个参数、多个参数、参数对象等。

  5. 结果集映射:MyBatis支持将SQL查询的结果集映射到Java对象,开发人员可以使用XML或注解来定义映射规则。

  6. 事务管理:MyBatis支持事务管理,可以通过编程方式管理事务,也可以配置自动提交或手动提交事务。

  7. 插件支持:MyBatis提供了插件机制,允许开发人员编写自定义插件来扩展其功能,例如添加日志、性能监控等。

  8. 集成性:MyBatis可以与Spring、Spring Boot等常见的Java框架和应用服务器集成,使其更容易在现有项目中使用。

  9. 易于学习和使用:MyBatis的学习曲线相对较低,它的配置和使用都相对简单明了。

        总之,MyBatis是一个轻量级的Java持久性框架,适用于需要直接访问数据库的应用程序。它提供了丰富的功能,包括SQL映射、参数映射、结果集映射等,使得数据库访问变得更加简单和灵活。

2、MyBatis的配置:

1、第一个是: mybatis-config.xml:

        当然这配置文件的名字不是固定死的,只是大家都这么叫就随大流好吧,然后是这配置文件的存放位置,这边也是大家默认的存入放在资源路径下也就是Resource路径下,(该路径就是类的根路径)。

<?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>
    <!--开启mybatis的标准日志 是mybatis已经实现的-->
    <!--<settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="10100109"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--执行XXMapper.xml的文件的路径-->
        <!--resource会从根路径下查找资源-->
        <mapper resource="CarMapper.xml"/>
        <!--<mapper url="file:///绝对路径"></mapper>-->
    </mappers>
</configuration>
1、environments:

        代表环境可以是多个,以“s”结尾表示复数,也就是说mybatis的环境可以配置多个数据源。其中default属性表示默认使用的是哪个环境,default后面填写的是environment的id。default的值只需要和environment的id值一致即可。

        environment作为子标签,具体的环境配置(主要包括:事务管理器的配置 + 数据源的配置)i其中id表示给当前环境一个唯一标识,该标识用在environments的default后面,用来指定默认环境的选择。

2、transactionManager:

        配置事务管理器,type属性指定事务管理器具体使用什么方式,可选值包括:

  1. JDBC:使用JDBC原生的事务管理机制。
  2. MANAGED:交给其它容器来管理事务,比如WebLogic、JBOSS等。如果没有管理事务的容器,则没有事务。没有事务的含义:只要执行一条DML语句,则提交一次
3、dataSource:

        用于指定数据源(给程序提供连接对象),type属性用来指定具体使用的数据库连接池的策略,可选值包括三个:

UNPOOLED:采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用数据库连接池的思想。所以使用sqlsessionFactory创建sqlsesion会话的时候,每一次创建都是一个新的会话对象,这样效率低而其不安全。

POOLED:采用传统的javax.sql.DataSource规范中的连接池,每一次创建连接都是从连接池中获取连接,可以限制连接的个数。一般使用连接池的话,需要配置参数。

 <!--最多有多少连接可以使用  默认是10-->
                <property name="poolMaximumActiveConnections" value="10"/>
                <!--最多空闲5个 当链接池中的空闲的连接数大于5的部分,连接池会将多出来的杀死-->
                <property name="poolMaximumIdleConnections" value="5"/>
                <!--每隔一秒打印日志,并且尝试连接-->
                <property name="poolTimeToWait" value="1000"/>
                <!--连接过期时间  十秒-->
                <property name="poolMaximumCheckoutTime" value="10000"/>

 

JNDI:使用其他第三方的数据库连接池

mappers:在mappers标签中可以配置多个sql映射文件的路径。

  • mapper:配置某个sql映射文件的路径
    • resource属性:使用相对于类路径的资源引用方式
    • url属性:使用完全限定资源定位符(URL)方式

2、第二个是:XXXMpaper.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="kkk">
    <insert id="insertCar">
        insert into  t_car (id,car_num,brand,guide_price,produce_time,car_type)
        values (null,'1220','BYD秦',20,'2020-1-1','电动车')
        </insert>
</mapper>

3、MyBatis完成CRUD:

1、Create(增):

<insert id="insertCar">
        insert into  t_car (id,car_num,brand,guide_price,produce_time,car_type)
        values (null,#{carNum},#{brand},#{guidingPrice},#{produceTime},#{carType})
        /*类的属性名*/
        </insert>

 Car类:

public class Car {
    private  Long id;
    private  String brand;
    private  String carNum;
    private  Double guidingPrice;
    private  String produceTime;
    private String carType;}

主要是根据get和set方法。

测试类:

 //插入数据
    @Test
    public void test4(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        Car car=new Car(null,"仰望U8","2222",90.0,"2022-2-2","混动");

        sqlSession.insert("insertCar",car);//sql语句的id,对象
        sqlSession.commit();
        sqlSession.close();
    }

2、delete(删):

<delete id="deleteByID">
        delete from  t_car where id =#{id}
    </delete>
   //删除数据
    @Test
    public void test5(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        sqlSession.delete("deleteByID",176);
        sqlSession.commit();
        sqlSession.close();
    }

3、update(改)

<update id="updateCar">
        update t_car set  car_num=#{carNum}, brand=#{brand}, guide_price=#{guidingPrice},car_type=#{carType} ,produce_time=#{produceTime} where id=#{id}
    </update>
//修改数据
    @Test
    public void test6(){
        SqlSession sqlSession = SqlSessionUtil.openSession();

        Car car = new Car(177L,"雪铁龙","3457",12.1,"2019-6-9","燃油");
        sqlSession.update("updateCar",car);
        sqlSession.commit();
        sqlSession.close();
    }

4、select(查): 

 查一个:

<select id="selectById" resultType="com.songzhishu.mybatis.pojo.Car">
        select id,
               brand,
               car_num      as carNum,
               guide_price  as guidingPrice,
               car_type     as carType,
               produce_time as produceTime
        from t_car
        where id = #{id}
    </select>

其中查询的配置文件中resultType指定啦查询结果封装的对象。这里有一个问题,查询的结果集的列名,有时候会和我们的定义类的属性不一致,就会导致数据封装的时候,会出现有的属性的值没有被封装上。所以面对不一致的时候我们要进行重命名

//查找数据 一条
    @Test
    public void test4(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        Object car = sqlSession.selectOne("selectById", 179);
        System.out.println(car);
        sqlSession.close();
    }

查全部:

<select id="selectAll" resultType="com.songzhishu.mybatis.pojo.Car">
        select id,
               brand,
               car_num      as carNum,
               guide_price  as guidingPrice,
               car_type     as carType,
               produce_time as produceTime
        from t_car
    </select>
//查找数据 一条
    @Test
    public void test5(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        List<Object> selectAll = sqlSession.selectList("selectAll");
        for (Object o : selectAll) {
            System.out.println(o);
        }
        sqlSession.close();
    }

4、MyBatis的参数处理:

1、单个简单参数:

  • byte         short          int         long         float         double         char
  • Byte         Short         Integer         Long         Float         Double         Character
  • String
  • java.util.Date
  • java.sql.Date

mapper:

/**
     * 测试接口中的方法只有一个参数,并且是简单类型的数据
     * id  long   name  string   brith  data  sex  char
     *
     */
    List<Student> selectById(Long id);
    List<Student> selectByName(String name);
    List<Student> selectByBrith(Date date);
    List<Student> selectBySex(Character sex);

mapper映射文件:

<!--
    parameterType 用来指定传递的参数的类型  可以不写  可以简写 比如java.lang.long 可以简写成long
    如果不写,mybatis可以自动推断出来传递过参数的类型
    -->
    <select id="selectById" resultType="Student" parameterType="long">
        select *
        from t_student
        where id = #{id}
    </select>
    <select id="selectByName" resultType="Student" parameterType="string">
        select *
        from t_student
        where name = #{name}
    </select>
    <select id="selectByBrith" resultType="Student" parameterType="date">
        select *
        from t_student
        where birth = #{birth}
    </select>
    <select id="selectBySex" resultType="Student">
        select *
        from t_student
        where sex = #{sex}
    </select>

test:

/*
     * 测试单个参数,数据类型是简单类型
     */
    @Test
    public void test1() throws ParseException {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //id
        List<Student> studentList = mapper.selectById(1L);
        for (Student student : studentList) {
            System.out.println(student);
        }
        System.out.println("------------");
        //name
        List<Student> studentList1 = mapper.selectByName("张三");
        for (Student student : studentList1) {
            System.out.println(student);
        }
        //data
        System.out.println("------------");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date brith=sdf.parse("2003-10-09");
        List<Student> studentList2 = mapper.selectByBrith(brith);
        for (Student student : studentList2) {
            System.out.println(student);
        }
        System.out.println("------------");
        //sex
        List<Student> studentList3 = mapper.selectBySex('男');
        for (Student student : studentList3) {
            System.out.println(student);
        }
    }

2、Map参数:

mapper接口:

 /**
     * 测试map集合类型
     */
    int insertStudentByMap(Map<String, Object> map);

mapper映射文件:

<insert id="insertStudentByMap" parameterType="map">
        insert into t_student(id,name,age,sex,height,birth)
        values (null,#{name},#{age},#{sex},#{height},#{birth});
    </insert>

测试类:

/**
     * map集合类型的参数
     */
    @Test
    public void test2() throws ParseException {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("name","张彩霞");//key是什么 然后取值的时候就
        map.put("sex",'女');
        map.put("height",166.0);
        map.put("age",45);
        map.put("birth",new Date());
        int count = mapper.insertStudentByMap(map);
        sqlSession.commit();
        sqlSession.close();
    }

3、对象类型:

mapper接口:

/**
     * 测试pojo类型
     */
    int insertStudentByPojo(Student student);

mapper映射文件:

 <insert id="insertStudentByPojo">
        insert into t_student(id,name,age,sex,height,birth)
        values (null,#{name},#{age},#{sex},#{height},#{birth});
    </insert>

测试类:

 /**
     * pojo类型
     */
    @Test
    public void test3() throws ParseException {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date brith1=sdf.parse("2003-11-29");
        Student student=new Student(null,"小蒋",19,163.0,brith1,'女');
        int count = mapper.insertStudentByPojo(student);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

 4、多参数:

mapper接口:

/**
     * 多参数类型
     */
    List<Student> selectByNameAndSex(String name,Character sex);

mapper映射文件:

<select id="selectByNameAndSex" resultType="Student">
        select *
        from t_student
        where name = #{arg0}
          and sex = #{arg1}
    </select>

测试类:

@Test
    public void test4(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.selectByNameAndSex("小蒋", '女');
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();

    }

总结:

        

        但是这种方式不太好吧,每一次写sql语句的时候,只能使用mybatis自带的这种命名规则嘛,这样的代码可读性也太差啦。所以就推出啦参数可以使用Param注解。

5、多参数之Param注解

mapper接口:

/**
     * 多参数类型  Param注解
     */
    List<Student> selectByHeightAndSex(@Param("sex") Character sex,@Param("height") Double height);

mapper樱色文件:

<select id="selectByHeightAndSex" resultType="Student">
        select *
        from t_student
        where height >#{height}
          and sex = #{sex}
    </select>

 测试类:

/**
     * 参数传递 Param注解
     */
    @Test
    public void test5(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.selectByHeightAndSex('女', 165.0);
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }

注意:

        使用Param注解后,arg不可以再使用,但是Param可以使用,但是没有比要,都已经命名啦,还使用没有注解的方式不是多此一举嘛。

6、 返回map集合:

        主要是针对查询出来的数据没有封装类的数据,用来存储到map集合里面。

(1)单个map:

mapper接口方法:

//使用map集合返回参数
    Map<String,Object>  selectByIdReturnMap(Long id);

mapper映射文件:

 <select id="selectByIdReturnMap" resultType="java.util.Map">
        select id,
               brand,
               car_num      as carNum,
               guide_price  as guidingPrice,
               car_type     as carType,
               produce_time as produceTime
        from t_car
        where id = #{id}
    </select>

测试类:

 //使用集合接收参数
    @Test
    public  void test10(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<String, Object> stringObjectMap = mapper.selectByIdReturnMap(179L);
        System.out.println(stringObjectMap);
        sqlSession.close();
    }
(2)多个map:

 mapper接口方法:

//获取多个map
    List<Map<String,Object>> selectByPriceReturnListMap(Double price);

mapper映射文件:

<select id="selectByPriceReturnListMap" resultType="java.util.Map">
        select id,
               brand,
               car_num      as carNum,
               guide_price  as guidingPrice,
               car_type     as carType,
               produce_time as produceTime
        from t_car
        where guide_price > #{price}
    </select>

测试类:

//返回多个map
    @Test
    public  void test11(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Map<String, Object>> list = mapper.selectByPriceReturnListMap(10.0);
        System.out.println(list);
        list.forEach(map -> {
            System.out.println(map);
        });
        sqlSession.close();
    
(3)返回Map<String,Map>:

  mapper接口方法:

//返回信息为map存储信息 map的key是每条记录的主键,value 是每一条数据(map)
    @MapKey("id")//将查询结果的id值作为大map的key
    Map<Long,Map<String,Object>> selectAllReturnMapMap(Double price);

mapper映射文件:

<select id="selectAllReturnMapMap" resultType="java.util.Map">
        select id,
               brand,
               car_num      as carNum,
               guide_price  as guidingPrice,
               car_type     as carType,
               produce_time as produceTime
        from t_car
        where guide_price > #{price}
    </select>

测试类:

//返回多个map
    @Test
    public  void test12(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<Long, Map<String, Object>> longMapMap = mapper.selectAllReturnMapMap(10.0);
        System.out.println(longMapMap);
        sqlSession.close();
    }
    

 总结:

        这里使用了@MapKey 的注解,使用这个的好处就是将查询结果的id值作为大Map的key,然后将其他的查询的结果作为map,Map<Long, Map<String, Object>>

7、resultMap结果映射:

查询结果的列名和java对象的属性名对应不上怎么办?

  • 第一种方式:as 给列起别名
  • 第二种方式:使用resultMap进行结果映射
  • 第三种方式:是否开启驼峰命名自动映射(配置settings)

        第一种方式的话已经写过啦,就不在这里进行叙述啦,然后下面就主要说明后面两种方式的使用方式。

(1)resultMap进行结果映射
<!--
            resultMap:
            id:这个结果映射的标识,作为select标签的resultMap属性的值。
            type:结果集要映射的类。可以使用别名。
    -->
    <resultMap id="carResultMap" type="com.songzhishu.mybatis.pojo.Car">
        <!--对象的唯一标识,官方解释是:为了提高mybatis的性能。建议写上。-->
        <id property="id" column="id"/>
        <result property="carNum" column="car_num"/>
        <!--当属性名和数据库列名一致时,可以省略。但建议都写上。-->
        <!--javaType用来指定属性类型。jdbcType用来指定列类型。一般可以省略。-->
        <result property="brand" column="brand" javaType="string" jdbcType="VARCHAR"/>
        <result property="guidingPrice" column="guide_price"/>
        <result property="produceTime" column="produce_time"/>
        <result property="carType" column="car_type"/>
    </resultMap>

解决方法就是在配置文件中配置resultMap ,然后就是使用

<select id="selectAllUseResultMap" resultMap="carResultMap">
        select * from t_car
    </select>

这时候不在使用resultType而是使用resultMap。

(2)开启驼峰命名自动映射:

        使用这种方式的前提是:属性名遵循Java的命名规范,数据库表的列名遵循SQL的命名规范。

Java命名规范:首字母小写,后面每个单词首字母大写,遵循驼峰命名方式。

SQL命名规范:全部小写,单词之间采用下划线分割。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值