MyBatis:mybatis Java API编程实现增删改查的用法
Posted yy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis:mybatis Java API编程实现增删改查的用法相关的知识,希望对你有一定的参考价值。
最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习:
Mybatis官网给了具体的文档,但是并没有对以上用法具体介绍,因此在这里整理下,以便以后工作用到时,可以参考。
本章主要增、删、改、查的用法进行学习(本章将结合Spring自动注入《Spring(二十三):Spring自动注入的实现方式》),下边文章分为以下几个步骤:
1)新建maven,并引入spring/mybatis/mybatis-spring/mysql/druid/junit包,新增配置spring-config.xml/mybaits-config.xml/jdbc.properties配置文件;
2)在mysql中新建mydb,并创建article,article_category两张表;
3)新增用法;
4)修改用法;
5)查询用法;
6)删除用法。
1)新建maven,并引入spring/mybatis/mybatis-spring/mysql/druid/junit包,新增配置spring-config.xml/mybaits-config.xml/jdbc.properties配置文件
新建一个maven项目(Learn-Spring-01,源码以上处至github:https://github.com/478632418/mybatis-spring-auto-annonation/tree/master/Learn-Spring-01),项目pom.xml中引入以下包:
spring相关包:
。。。。。
<org.springframework.version>5.2.0.RELEASE</org.springframework.version> <org.mybatis.version>3.4.6</org.mybatis.version> <com.alibaba.version>1.1.21</com.alibaba.version> <mysql.version>8.0.11</mysql.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.4</version> </dependency> <!-- Sping Test相关依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> </dependency> 。。。
mybatis、mybatis-spring包
<!--MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${org.mybatis.version}</version> </dependency> <!-- Mybatis自身实现的Spring整合依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.3</version> </dependency>
mysql和druid包
<!--MySql数据库驱动 --> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${com.alibaba.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency>
junit包:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
新建以下类:
实体类:
com.dx.test.model.Article.java
package com.dx.test.model; import java.util.Date; /** * 文章详情 */ public class Article { private Long id; // 文章id private String title; // 文章标题 private String content; // 文章内容 private Integer categoryId; // 文章分类id private String createUser; // 新建用户 private String createUserId;// 新建用户id private Date createTime; // 新建时间 private String updateUser; // 修改用户 private String updateUserId;// 修改用户id private Date updateTime; // 修改时间 private Integer version; // 乐观锁版本号 private ArticleCategory articleCategory; // [扩展字段]文章分类实体 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getCreateUserId() { return createUserId; } public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public String getUpdateUserId() { return updateUserId; } public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public ArticleCategory getArticleCategory() { return articleCategory; } public void setArticleCategory(ArticleCategory articleCategory) { this.articleCategory = articleCategory; } @Override public String toString() { return "Article [id=" + id + ", title=" + title + ", content=" + content + ", categoryId=" + categoryId + ", articleCategory=" + articleCategory + "]"; } }
com.dx.test.model.ArticleCategory.java
package com.dx.test.model; import java.util.Date; /** * 文章分类 * */ public class ArticleCategory { private Integer id; //文章分类id private String title; // 文章分类名称 private String imgSrc; // 文章分类banner图片 private String description; // 文章分类描述 private String createUser; // 新建用户 private String createUserId;// 新建用户id private Date createTime; // 新建时间 private String updateUser; // 修改用户 private String updateUserId;// 修改用户id private Date updateTime; // 修改时间 private Integer version; // 乐观锁版本号 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImgSrc() { return imgSrc; } public void setImgSrc(String imgSrc) { this.imgSrc = imgSrc; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getCreateUserId() { return createUserId; } public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public String getUpdateUserId() { return updateUserId; } public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } @Override public String toString() { return "ArticleCategory [id=" + id + ", title=" + title + ", imgSrc=" + imgSrc + ", description=" + description + "]"; } }
Mybatis Java API mapper类:
com.dx.test.mapper.sqlprovider.ArticleMapper.java
com.dx.test.mapper.sqlprovider.ArticleCategoryMapper.java
Mybatis Java API mapper的sql生成类:
com.dx.test.mapper.sqlprovider.ArticleSqlProvder.java
com.dx.test.mapper.sqlprovider.ArticleCategorySqlProvder.java
Repository层(类上都使用@Repository注解):
com.dx.test.repository.ArticleDao.java
com.dx.test.repository.ArticleCategoryDao.java
Service层(类上都使用@Service注解):
com.dx.test.service.ArticleService.java
com.dx.test.service.ArticleCategoryService.java
包含main入口类:
com.dx.test.App.java
在/src/main/resources下新建jdbc.properties、mybatis-config.xml、spring-config.xml配置文件:
1)jdbc.properties中配置mysql的user/pwd/url/driver/其他先关配置;
2)mybatis-config.xml配置mybatis配置;
3)spring-config.xml配置spring自动注入,以及mybatis整合。
jdbc.properties
#jdbc settings jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false jdbc.username=root jdbc.password=123456 #pool settings jdbc.pool.init=1 jdbc.pool.minIdle=3 jdbc.pool.maxActive=20 #jdbc.testSql=SELECT \'x\' jdbc.testSql=SELECT \'x\' FROM DUAL
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> <!--配置全局属性--> <settings> <!-- 打开延迟加载的开关 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 将积极加载改为消极加载(即按需加载) --> <setting name="aggressiveLazyLoading" value="false"/> <!-- 打开全局缓存开关(二级缓存)默认值就是 true --> <setting name="cacheEnabled" value="true"/> <!--使用jdbc的getGeneratekeys获取自增主键值--> <setting name="useGeneratedKeys" value="true"/> <!--使用列别名替换别名 默认true select name as title form table; --> <setting name="useColumnLabel" value="true"/> <!--开启驼峰命名转换--> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--打印sql日志--> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!-- 引用db.properties配置文件 --> <!-- <properties resource="db.properties"/> <typeAliases> <package name="com.dx.test.model"/> </typeAliases> --> <!-- 对事务的管理和连接池的配置 --> <!-- <environments default="mysql_jdbc"> <environment id="oracle_jdbc"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${name}"/> <property name="password" value="${password}"/> </dataSource> </environment> <environment id="mysql_jdbc"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${name}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> --> <!-- <mappers> <mapper resource="resources/mapper/TaskAutoExecutePlanMapper.xml"/> </mappers> --> <mappers> <mapper class="com.dx.test.mapper.ArticleCategoryMapper"></mapper> <mapper class="com.dx.test.mapper.ArticleMapper"></mapper> </mappers> </configuration>
备注:
1)因这里采用的是mybatis与spring整合,因此mysql先关数据源信息不在mybatis-config.xml中配置,而是配置spring-config.xml的dataSource的bean下;
2)mappers节点下的mapper需要指定mapper类,又因这里是采用的mybatis java api方式(只需要在ArticleCategoryMapper和ArticleMapper上添加上@Mapper注解即可),因此不再需要配置*Mapper.xml。
spring-config.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="com.dx.test.repository,com.dx.test.mapper,com.dx.test.service" /> <!-- 配置整合Mybatis过程 --> <!-- 配置数据库相关参数 properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> --> <!--2.配置连接池属性 --> <!-- 数据源配置, 使用 Druid 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass --> <property name="driverClassName" value="${jdbc.driver}"/> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> Mybatis-动态SQL