网站推广教程优化整站,wordpress怎么新建子域名,网站建设公司赚钱吗,如何在工商局网站做身份确认1. MyBatis 的注解式开发 文章目录 1. MyBatis 的注解式开发2. 准备工作3. Insert 插入/添加4. Delete 删除5. Update 更新/修改6. Select 查询7. 总结#xff1a;8. 最后#xff1a; MyBatis 中也提供了注解式开发方式#xff0c;采用注解可以减少Sql映射文件的配置。
当然…1. MyBatis 的注解式开发 文章目录 1. MyBatis 的注解式开发2. 准备工作3. Insert 插入/添加4. Delete 删除5. Update 更新/修改6. Select 查询7. 总结8. 最后 MyBatis 中也提供了注解式开发方式采用注解可以减少Sql映射文件的配置。
当然使用注解式开发的话sql语句是写在java程序中的这种方式也会给sql语句的维护带来成本。
官方是这么说的 使用注解来映射简单语句会使代码显得更加简洁但对于稍微复杂一点的语句(比如含有 ,标签 )Java 注解不仅力不从心还会让你本就复杂的 SQL 语句更加混乱不堪。 因此如果你需要做一些很复杂的操作最好用 XML 来映射语句。 使用注解编写复杂的SQL是这样的 原则简单SQL 可以注解。复杂SQL 建议使用 xmlSQL映射文件。 2. 准备工作
数据表结构的设计数据表名为t_car t_car 表中的数据信息 在pom.xml 文件当中配置相关的依赖的 jar 包如下 ?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdcom.rainbowsea/groupIdartifactIdmybatis-005-crud-blog/artifactIdversion1.0-SNAPSHOT/versionpropertiesmaven.compiler.source17/maven.compiler.sourcemaven.compiler.target17/maven.compiler.target/propertiesdependencies!-- mybatis 的依赖--dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.10/version/dependency!-- mysql --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.30/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13.2/versionscopetest/scope/dependency!-- 引入 logback的依赖这个日志框架实现了slf4j 规范--dependencygroupIdch.qos.logback/groupIdartifactIdlogback-classic/artifactIdversion1.2.11/version/dependency/dependencies/project配置 logback 的配置文件用于打印显示我们的日志信息方便我们查看我们的运行过程效果。 ?xml version1.0 encodingUTF-8?configuration debugfalse!-- 控制台输出 --appender nameSTDOUT classch.qos.logback.core.ConsoleAppenderencoder classch.qos.logback.classic.encoder.PatternLayoutEncoder!--格式化输出%d表示日期%thread表示线程名%-5level级别从左显示5个字符宽度%msg日志消息%n是换行符--pattern%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n/pattern/encoder/appender!--mybatis log configure--logger namecom.apache.ibatis levelTRACE/logger namejava.sql.Connection levelDEBUG/logger namejava.sql.Statement levelDEBUG/logger namejava.sql.PreparedStatement levelDEBUG/!-- 日志输出级别,logback日志级别包括五个TRACE DEBUG INFO WARN ERROR --root levelDEBUGappender-ref refSTDOUT/appender-ref refFILE//root/configuration配置 MyBatis 的核心配置文件 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd
configuration!-- 使用 package 还可以将这个包下的所有的类的全部自动起别名别名就是简名不区分大小写 --package namecom.rainbowsea.mybatis.pojo//typeAliasesenvironments defaultmybatisenvironment idmybatis!-- MANAGED 没有用第三框架管理的话都是会被提交的没有事务上的管理了 --transactionManager typeJDBC/dataSource typePOOLEDproperty namedriver valuecom.mysql.cj.jdbc.Driver/property nameurl valuejdbc:mysql://localhost:3306/mybatis/property nameusername valueroot/property namepassword valueMySQL123//dataSource/environment/environmentsmappers!-- 这里也是可以使用 package 包名扫描但是同样的对应接口路径要一致接口名一致--package namecom.rainbowsea.mybatis.mapper/package/mappers
/configuration对照 t_car 创建的ORM 映射的 Car 类
注意在MyBatis 当中对应的ORM 一般在框架里对应的 Bean实体类一定要实现该 set 和 get 方法以及无参数构造方法无法框架无法使用反射机制进行操作 。
建议用包装类这样可以防止 Null的问题因为简单类型 int num null 是不可以赋值为 null的编译无法通过 package com.rainbowsea.mybatis.pojo;public class Car {// 数据库表当中的字段应该和pojo类的属性一一对应// 建议使用包装类这样可以防止null的问题private Long id;private String carNum;private String brand;private Double guidePrice;private String produceTime;private String carType;public Car() {}public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {this.id id;this.carNum carNum;this.brand brand;this.guidePrice guidePrice;this.produceTime produceTime;this.carType carType;}Overridepublic String toString() {return Car{ id id , carNum carNum \ , brand brand \ , guidePrice guidePrice , produceTime produceTime \ , catType carType \ };}public Long getId() {return id;}public void setId(Long id) {this.id id;}public String getCarNum() {return carNum;}public void setCarNum(String carNum) {this.carNum carNum;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand brand;}public Double getGuidePrice() {return guidePrice;}public void setGuidePrice(Double guidePrice) {this.guidePrice guidePrice;}public String getProduceTime() {return produceTime;}public void setProduceTime(String produceTime) {this.produceTime produceTime;}public String getcarType() {return carType;}public void setcarType(String catType) {this.carType catType;}
}
3. Insert 插入/添加
直接用注解不需要写对应的 SQl映射文件。 import com.rainbowsea.mybatis.pojo.Car;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;public interface CarMapper {Insert(insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType}))int insert(Car car);}运行测试 Testpublic void testInsert() throws IOException {SqlSessionFactoryBuilder sqlSessionFactoryBuilder new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory sqlSessionFactoryBuilder.build(Resources.getResourceAsStream(mybatis -config.xml), mybatis);SqlSession sqlSession sqlSessionFactory.openSession();CarMapper mapper sqlSession.getMapper(CarMapper.class);Car car new Car(null,666,丰田霸道,new BigDecimal(32.00),2020-11-11,燃油车);int count mapper.insert(car);System.out.println(count);sqlSession.commit();sqlSession.close();}4. Delete 删除 import com.rainbowsea.mybatis.pojo.Car;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;public interface CarMapper {Delete(delete from t_car where id #{id})int deleteById(Long id);}运行测试 Testpublic void testDeleteById() throws IOException {SqlSessionFactoryBuilder sqlSessionFactoryBuilder new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory sqlSessionFactoryBuilder.build(Resources.getResourceAsStream(mybatis -config.xml), mybatis);SqlSession sqlSession sqlSessionFactory.openSession();CarMapper mapper sqlSession.getMapper(CarMapper.class);int count mapper.deleteById(139L);System.out.println(count);sqlSession.commit();sqlSession.close();}5. Update 更新/修改 import com.rainbowsea.mybatis.pojo.Car;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;public interface CarMapper {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);}运行测试 Testpublic void testUpdate() throws IOException {SqlSessionFactoryBuilder sqlSessionFactoryBuilder new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory sqlSessionFactoryBuilder.build(Resources.getResourceAsStream(mybatis -config.xml), mybatis);SqlSession sqlSession sqlSessionFactory.openSession();CarMapper mapper sqlSession.getMapper(CarMapper.class);Car car new Car(139L,666,丰田霸道2,new BigDecimal(32.00),2020-11-11,燃油车);int count mapper.update(car);System.out.println(count);sqlSession.commit();sqlSession.close();}6. Select 查询 import com.rainbowsea.mybatis.pojo.Car;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;public interface CarMapper {Select(select * from t_car where id #{id})Car selectById(Long id);}运行测试 import com.rainbowsea.mybatis.mapper.CarMapper;
import com.rainbowsea.mybatis.pojo.Car;
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 org.junit.Test;import java.io.IOException;
import java.math.BigDecimal;public class CarMapperTest {Testpublic void testSelectById() throws IOException {SqlSessionFactoryBuilder sqlSessionFactoryBuilder new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory sqlSessionFactoryBuilder.build(Resources.getResourceAsStream(mybatis -config.xml), mybatis);SqlSession sqlSession sqlSessionFactory.openSession();CarMapper mapper sqlSession.getMapper(CarMapper.class);Car car mapper.selectById(118L);System.out.println(car);sqlSession.close();}
}7. 总结 原则简单SQL 可以注解。复杂SQL 建议使用 xmlSQL映射文件。 8. 最后 “在这个最后的篇章中我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底继续在其他的领域奋斗。感谢你们我们总会在某个时刻再次相遇。”