首页 > 其他分享 >mybatis的注解开发

mybatis的注解开发

时间:2023-06-10 13:33:25浏览次数:32  
标签:mapper car sqlSession 开发 Car mybatis 注解 CarMapper id

1. 基本介绍  130

mybatis中也提供了注解式开发⽅式,采⽤注解可以减少Sql映射⽂件的配置。

当然,使⽤注解式开发的话,sql语句是写在java程序中的,这种⽅式也会给sql语句的维护带来成本。

官⽅是这么说的:使⽤注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂⼀点的语句,Java 注解不仅⼒不从⼼,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做⼀些很复杂的操作,最好⽤ XML 来映射语句。

2. 使⽤注解编写复杂的SQL是这样的:

mybatis的注解开发_Test

原则:简单sql可以注解。复杂sql使⽤xml。

打包⽅式:jar

依赖:mybatis,mysql驱动,junit,logback

配置⽂件:jdbc.properties、mybatis-config.xml、logback.xml

pojo:com.powernode.mybatis.pojo.Car

mapper接⼝:com.powernode.mybatis.mapper.CarMapper

2.1 增加数据  130

@Insert("insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})")
    int insert(Car car);
//插入数据  130
    @Test
    public void testInsert(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(null,"6666","丰田霸道",32.0,"2020-11-11","燃油车");
        int count = mapper.insert(car);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

mybatis的注解开发_xml_02

2.2 删除数据  131

@Delete("delete from t_car where id = #{id}")
    int deleteById(Long id);
//删除数据  131
    @Test
    public void testDeleteById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.deleteById(48L);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

mybatis的注解开发_Test_03

2.3 更新数据  132

@Update("update t_car set car_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType} where id=#{id}")
    int update(Car car);
//更新数据  132
    @Test
    public void testUpdate(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(6L,"6666","丰田霸道",32.0,"2020-11-11","燃油车");
        int count = mapper.update(car);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

mybatis的注解开发_Test_04

2.4 查询数据  133-134

@Select("select * from t_car where id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "carNum", column = "car_num"),
            @Result(property = "brand", column = "brand"),
            @Result(property = "guidePrice", column = "guide_price"),
            @Result(property = "produceTime", column = "produce_time"),
            @Result(property = "carType", column = "car_type")
    })
    Car selectById(Long id);
//查询数据  133
    @Test
    public void testSelectById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(43L);
        System.out.println(car);
        sqlSession.close();
    }

mybatis的注解开发_xml_05

3. 代码汇总

main中com.powernode.mybatis.mapper

CarMapper

package com.powernode.mybatis.mapper;

import com.powernode.mybatis.pojo.Car;
import org.apache.ibatis.annotations.*;

//注解式开发  130
public interface CarMapper {
    @Select("select * from t_car where id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "carNum", column = "car_num"),
            @Result(property = "brand", column = "brand"),
            @Result(property = "guidePrice", column = "guide_price"),
            @Result(property = "produceTime", column = "produce_time"),
            @Result(property = "carType", column = "car_type")
    })
    Car selectById(Long id);

    @Update("update t_car set car_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType} where id=#{id}")
    int update(Car car);

    @Insert("insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})")
    int insert(Car car);

    @Delete("delete from t_car where id = #{id}")
    int deleteById(Long id);
}

test中com.powernode.mybatis.test

CarMapperTest

package com.powernode.mybatis.test;

import com.powernode.mybatis.mapper.CarMapper;
import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

//注解式开发  130
public class CarMapperTest {

    //查询数据  133
    @Test
    public void testSelectById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(43L);
        System.out.println(car);
        sqlSession.close();
    }

    //更新数据  132
    @Test
    public void testUpdate(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(6L,"6666","丰田霸道",32.0,"2020-11-11","燃油车");
        int count = mapper.update(car);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

    //删除数据  131
    @Test
    public void testDeleteById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.deleteById(48L);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

    //插入数据  130
    @Test
    public void testInsert(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = new Car(null,"6666","丰田霸道",32.0,"2020-11-11","燃油车");
        int count = mapper.insert(car);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }
}

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"/>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.powernode.mybatis.pojo"/>
    </typeAliases>


    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.powernode.mybatis.mapper"/>
    </mappers>
</configuration>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.powernode</groupId>
    <artifactId>course26</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>
    </dependencies>


    <properties>
        <!--    编译代码使用的jdk版本-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <!--    运行程序使用的jdk版本-->
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

</project>

剩余的

pojo

utils

logback.xml

jdbc.properties

不做赘述

标签:mapper,car,sqlSession,开发,Car,mybatis,注解,CarMapper,id
From: https://blog.51cto.com/u_15784725/6454473

相关文章

  • 使用Mybatis框架(xml)
    结构: Pojo实体类,对应mysql表的结构 mapper,将sql映射成方法,通过demo去调用sql方法XXXmaaper.xml里面写了具体的sqllogback.xml、mybatis.xml配置信息使用mapper去代理开发要将XXXmapper.xml配置和mapper方法类放在同一目录下 XXXmapper.xml具体类的配置:<?xmlversion......
  • 投票活动小程序开发搭建
    由于小程序是基于微信开发者工具编写的,因此我先介绍一下需要使用的工具和技术:-微信开发者工具:用于开发、调试和发布小程序。-小程序云开发:用于存储数据和进行后端逻辑处理。-uni-app框架:uni-app是一个使用Vue.js开发所有前端应用的框架,开发者编写一套代码,可发布到iOS、Androi......
  • Mybatis三
    $和#符号的区别{}相当于是预处理语句,会将#换成占位符?,字符串等数据赋值时自动拼接引号,可以避免SQL注入${}相当于是处理语句,直接原样将数据取出,直接拼接Mybatis缓存缓存主要目的是为了提高查询效率.缓存其实就是一个内存空间,存储在程序的某个地方,存储数据.......
  • 基于spring boot+mybatis+easyui开发的粮油MES系统源码
    粮油生产加工MES追溯系统源码粮油生产加工MES追溯系统,支持全流程生产溯源粮油MES质量管控防伪溯源系统可广泛用于粮油生产加工领域。实现种植主体、种植基地、生产计划、压榨、精炼、包装、销售、物料管理、检验检测等各个环节的数据采集,达到正向可追踪,反向可溯源,确保粮油品质。基......
  • Mybatis二
    编码格式错误控制台错误提示:MalformedByteSequenceException:1字节的UTF-8序列的字节1无效。解决方案,在pom文件中加入配置<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>分页插件现在我们要学习使用一个常用的......
  • ble开发-低电量管理
    现有客户需求,低电量模式进行操作后LED进行闪烁,不操作则闪三秒后结束首先对电量获取进行分析,其是通过ADC回调函数进行获取电量,然后如果电量发生变化则通过蓝牙发送电量变化后的值,ADC获取电量函数如下,当大于3V时 battery_percent电量值为100,低于1.8V则为0  _ATTR_SECTION_SR......
  • 开发一个简易的Start
    创建一个Springboot项目导入依赖整体项目结构图删除build<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=......
  • 陪诊陪护预约小程序开发可以提供哪些服务
    陪诊陪护预约小程序开发可以提供哪些服务?1、快速找陪护护工小程序开发基于地理位置,方便子女搜索陪护,手指一点轻松下单,预约陪护人员操作简单。2、护理认证护工需要实名认证、国家卫生部颁发的护士证月嫂证等有效证件认证等,需要面试后择优录取。3、住院陪护护工小程序可以预约医院的......
  • mybatis-动态构建SQL
    又学习到了,今天翻着队友写的代码,我看到了个注解,起初还以为是自定义的,我搜了下才发现,竟然是mybatis自带的这个注解,我竟然不知道,又是孤陋寡闻的一天,记录一下这个注解。查找了下这个注解发现这个注解是四个:我看了下与@Select有啥区别,这个@SelectProvider是能够加多条件判断的,看下面......
  • 靳宇灵 | FastAdmin数据库开发规则
    这里提供的是数据库表字段规则在你创建表时使用,当按如下的规则进行字段命名、类型设置和备注时使用phpthinkcrud-t表名生成CRUD时会自动生成对应的控制器、模型、视图、JS等。根据字段类型类型备注类型说明int整型自动生成type为number的文本框,步长为1enum枚举型自动生成单选下......