mybatis java api_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配置文件

spring相关包:

。。。。。

5.2.0.RELEASE

3.4.6

1.1.21

8.0.11

org.springframework

spring-webmvc

${org.springframework.version}

org.springframework

spring-tx

${org.springframework.version}

org.springframework

spring-jdbc

${org.springframework.version}

org.springframework

spring-core

${org.springframework.version}

org.springframework

spring-beans

${org.springframework.version}

org.springframework

spring-context

${org.springframework.version}

org.springframework

spring-context-support

${org.springframework.version}

org.springframework

spring-aop

${org.springframework.version}

aspectj

aspectjweaver

1.5.4

aspectj

aspectjrt

1.5.4

org.springframework

spring-test

${org.springframework.version}

。。。

mybatis、mybatis-spring包

org.mybatis

mybatis

${org.mybatis.version}

org.mybatis

mybatis-spring

2.0.3

mysql和druid包

com.alibaba

druid

${com.alibaba.version}

mysql

mysql-connector-java

${mysql.version}

junit包:

junit

junit

4.12

test

新建以下类:

实体类:

com.dx.test.model.Article.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.dx.test.model;importjava.util.Date;/*** 文章详情*/

public classArticle {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; //[扩展字段]文章分类实体

publicLong getId() {returnid;

}public voidsetId(Long id) {this.id =id;

}publicString getTitle() {returntitle;

}public voidsetTitle(String title) {this.title =title;

}publicString getContent() {returncontent;

}public voidsetContent(String content) {this.content =content;

}publicInteger getCategoryId() {returncategoryId;

}public voidsetCategoryId(Integer categoryId) {this.categoryId =categoryId;

}publicString getCreateUser() {returncreateUser;

}public voidsetCreateUser(String createUser) {this.createUser =createUser;

}publicString getCreateUserId() {returncreateUserId;

}public voidsetCreateUserId(String createUserId) {this.createUserId =createUserId;

}publicDate getCreateTime() {returncreateTime;

}public voidsetCreateTime(Date createTime) {this.createTime =createTime;

}publicString getUpdateUser() {returnupdateUser;

}public voidsetUpdateUser(String updateUser) {this.updateUser =updateUser;

}publicString getUpdateUserId() {returnupdateUserId;

}public voidsetUpdateUserId(String updateUserId) {this.updateUserId =updateUserId;

}publicDate getUpdateTime() {returnupdateTime;

}public voidsetUpdateTime(Date updateTime) {this.updateTime =updateTime;

}publicInteger getVersion() {returnversion;

}public voidsetVersion(Integer version) {this.version =version;

}publicArticleCategory getArticleCategory() {returnarticleCategory;

}public voidsetArticleCategory(ArticleCategory articleCategory) {this.articleCategory =articleCategory;

}

@OverridepublicString toString() {return "Article [id=" + id + ", title=" + title + ", content=" +content+ ", categoryId=" + categoryId + ", articleCategory=" + articleCategory + "]";

}

}

View Code

com.dx.test.model.ArticleCategory.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.dx.test.model;importjava.util.Date;/*** 文章分类

**/

public classArticleCategory {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; //乐观锁版本号

publicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}publicString getTitle() {returntitle;

}public voidsetTitle(String title) {this.title =title;

}publicString getImgSrc() {returnimgSrc;

}public voidsetImgSrc(String imgSrc) {this.imgSrc =imgSrc;

}publicString getDescription() {returndescription;

}public voidsetDescription(String description) {this.description =description;

}publicString getCreateUser() {returncreateUser;

}public voidsetCreateUser(String createUser) {this.createUser =createUser;

}publicString getCreateUserId() {returncreateUserId;

}public voidsetCreateUserId(String createUserId) {this.createUserId =createUserId;

}publicDate getCreateTime() {returncreateTime;

}public voidsetCreateTime(Date createTime) {this.createTime =createTime;

}publicString getUpdateUser() {returnupdateUser;

}public voidsetUpdateUser(String updateUser) {this.updateUser =updateUser;

}publicString getUpdateUserId() {returnupdateUserId;

}public voidsetUpdateUserId(String updateUserId) {this.updateUserId =updateUserId;

}publicDate getUpdateTime() {returnupdateTime;

}public voidsetUpdateTime(Date updateTime) {this.updateTime =updateTime;

}publicInteger getVersion() {returnversion;

}public voidsetVersion(Integer version) {this.version =version;

}

@OverridepublicString toString() {return "ArticleCategory [id=" + id + ", title=" + title + ", imgSrc=" + imgSrc + ", description=" +description+ "]";

}

}

View Code

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

/p>

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

备注:

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

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 ">

备注:

上边配置文件spring-config.xml配置包含两大部分配置:

1)spring自动注入配置;

2)spring注入sqlSessionFatcory到mybatis:

2.1)引入jdbc.properties配置信息到配置文件中;

2.2)dataSource bean的定义,这里采用的是com.alibaba.druid.pool.DruidDataSource作为dataSource实例;

2.3)使用sqlSessionFactory bean,需要引入mybatis-config.xml配置、dataSource bean实例;

2.4)使用org.mybatis.spring.mapper.MapperScannerConfigurer试下扫描mapper包路径下mapper,并关联上sqlSesssionFactory;

2.5)事务管理。

2)在mysql中新建mydb,并创建article,article_category两张表

SETNAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;--------------------------------Table structure for article------------------------------

DROP TABLE IF EXISTS`article`;CREATE TABLE`article` (

`id`bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增id',

`category_id`int(11) NOT NULL COMMENT '文章分类id',

`title`varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '文章标题',

`content`varchar(2048) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '文章内容',

`create_user`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '新建人',

`create_user_id`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '新建人id',

`create_time` dateNOT NULL COMMENT '新建时间',

`update_user`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '修改人',

`update_user_id`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '修改人id',

`update_time` dateNOT NULL COMMENT '修改时间',

`version`int(11) NOT NULL,PRIMARY KEY(`id`),KEY`idx_category_id` (`category_id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;--------------------------------Table structure for article_category------------------------------

DROP TABLE IF EXISTS`article_category`;CREATE TABLE`article_category` (

`id`int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',

`title`varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '文章分类名称',

`img_src`varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文章分类banner图片',

`description`varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文章分类描述',

`create_user`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '新建人',

`create_user_id`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '新建人id',

`create_time` dateNOT NULL COMMENT '新建时间',

`update_user`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '修改人',

`update_user_id`varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '修改人id',

`update_time` dateNOT NULL COMMENT '修改时间',

`version`int(11) NOT NULL,PRIMARY KEY(`id`)

) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;

新建数据库mydb,并新建article(文章表)、article_category(文章分类表)

3)新增用法

Mybatis Java API mapper类:

com.dx.test.mapper.sqlprovider.ArticleMapper.java

com.dx.test.mapper.sqlprovider.ArticleCategoryMapper.java

ArticleMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleMapper {/*** 入库分类

*

*@paramarticleCategory 待入库实体

*@return影响条数*/@Options(useCache= true, flushCache = Options.FlushCachePolicy.TRUE, useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")

@InsertProvider(type= ArticleSqlProvider.class, method = "insert")intinsert(Article article);

}

ArticleCategoryMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleCategoryMapper {/*** 入库文章分类

*

*@paramarticleCategory 待入库实体

*@return影响条数*/@Options(useCache= true, flushCache = Options.FlushCachePolicy.TRUE, useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")

@InsertProvider(type= ArticleCategorySqlProvider.class, method = "insert")intinsert(ArticleCategory articleCategory);

}

Mybatis Java API mapper的sql生成类:

com.dx.test.mapper.sqlprovider.ArticleSqlProvder.java

com.dx.test.mapper.sqlprovider.ArticleCategorySqlProvder.java

ArticleSqlProvider.java

packagecom.dx.test.mapper.sqlprovider;

。。。public classArticleSqlProvider {/*** 生成文章入库SQL

*

*@paramarticle 待插入文章实体

*@return生成SQL*/

public String insert(finalArticle article) {return newSQL() {

{

INSERT_INTO("article");

INTO_COLUMNS("title", "content", "category_id", "create_user", "create_user_id", "create_time","update_user", "update_user_id", "update_time", "version");

INTO_VALUES("#{title}", "#{content}", "#{categoryId}", "#{createUser}", "#{createUserId}","now()", "#{updateUser}", "#{updateUserId}", "now()", "0");

}

}.toString();

}

}

ArticleCategorySqlProvider.java

packagecom.dx.test.mapper.sqlprovider;

。。。public classArticleCategorySqlProvider {/*** 生成插入文章分类的SQL

*@paramarticleCategory文章分类

*@return返回插入文章SQL

**/

publicString insert(ArticleCategory articleCategory) {return newSQL() {{

INSERT_INTO("article_category");

INTO_COLUMNS("title","img_src","description", "create_user", "create_user_id", "create_time","update_user", "update_user_id", "update_time", "version");

INTO_VALUES("#{title}","#{imgSrc}","#{description}","#{createUser}", "#{createUserId}","now()", "#{updateUser}", "#{updateUserId}", "now()", "0");

}}.toString();

}

}

Repository层(类上都使用@Repository注解):

com.dx.test.repository.ArticleDao.java

com.dx.test.repository.ArticleCategoryDao.java

ArticleDao.java

packagecom.dx.test.repository;

。。。

@Repositorypublic class ArticleDao implementsArticleMapper {

@Autowired()privateArticleMapper articleMapper;

@Overridepublic intinsert(Article article) {return this.articleMapper.insert(article);

}

}

ArticleCategoryDao.java

packagecom.dx.test.repository;。。。

@Repositorypublic class ArticleCategoryDao implementsArticleCategoryMapper {

@AutowiredprivateArticleCategoryMapper articleCategoryMapper;/*** 插入文章分类

*@paramarticleCategory 插入文章分类

*@return相应条数

**/@Overridepublic intinsert(ArticleCategory articleCategory) {int result= this.articleCategoryMapper.insert(articleCategory);returnresult;

}

}

Service层(类上都使用@Service注解):

com.dx.test.service.ArticleService.java

com.dx.test.service.ArticleCategoryService.java

ArticleService.java

packagecom.dx.test.service;

...

@Servicepublic class ArticleService implementsArticleMapper{

@AutowiredprivateArticleDao articleDao;

@Overridepublic intinsert(Article article) {return this.articleDao.insert(article);

}

}

ArticleCategoryService.java

packagecom.dx.test.service;

...

@Servicepublic class ArticleCategoryService implementsArticleCategoryMapper {

@AutowiredprivateArticleCategoryDao articleCategoryDao;

@Overridepublic intinsert(ArticleCategory articleCategory) {return this.articleCategoryDao.insert(articleCategory);

}

}

4)修改用法

Mybatis Java API mapper类:

com.dx.test.mapper.sqlprovider.ArticleMapper.java

com.dx.test.mapper.sqlprovider.ArticleCategoryMapper.java

ArticleMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleMapper {/*** 根据文章id,删除文章

*

*@paramid 文章id

*@return影响条数*/@Options(useCache= true, flushCache =Options.FlushCachePolicy.TRUE)

@UpdateProvider(type= ArticleSqlProvider.class, method = "update")intupdate(Article article);

}

ArticleCategoryMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleCategoryMapper {/*** 根据文章id,删除文章

*

*@paramid 文章id

*@return影响条数*/@Options(useCache= true, flushCache =Options.FlushCachePolicy.TRUE)

@UpdateProvider(type= ArticleCategorySqlProvider.class, method = "update")intupdate(ArticleCategory articleCategory);

}

Mybatis Java API mapper的sql生成类:

com.dx.test.mapper.sqlprovider.ArticleSqlProvder.java

com.dx.test.mapper.sqlprovider.ArticleCategorySqlProvder.java

ArticleSqlProvder.java

packagecom.dx.test.mapper.sqlprovider;

。。。public classArticleSqlProvider {public String update(finalArticle article) {

StringBuilder sql= newStringBuilder();

sql.append("update `article` set `id`=#{id}");if (article.getCategoryId() != null) {

sql.append(", `category_id`=#{categoryId}");

}if (article.getTitle() != null) {

sql.append(", `title`=#{title}");

}if (article.getContent() != null) {

sql.append(", `content`=#{content}");

}if (article.getCreateUser() != null) {

sql.append(", `create_user` = #{createUser}");

}if (article.getCreateUserId() != null) {

sql.append(", `create_user_id` = #{createUserId}");

}

sql.append(", `update_time` = now()");if (article.getUpdateUser() != null) {

sql.append(", `update_user` = #{updateUser}");

}if (article.getUpdateUserId() != null) {

sql.append(", `update_user_id` = #{updateUserId}");

}

sql.append(", `version` = `version` + 1");

sql.append(" WHERE `id` = #{id} AND `version` = #{version}");returnsql.toString();

}

}

ArticleCategorySqlProvder.java

packagecom.dx.test.mapper.sqlprovider;

。。。public classArticleCategorySqlProvider {/*** 生成修改文章分类SQL

*@paramarticleCategory 文章分类实体

*@return返回修改文章分类SQL

**/

publicString update(ArticleCategory articleCategory) {

StringBuilder sql=newStringBuilder();

sql.append("update `article_category` set id=#{id}");if (articleCategory.getTitle() != null) {

sql.append(", `title`=#{title}");

}if (articleCategory.getImgSrc() != null) {

sql.append(", `img_src`=#{imgSrc}");

}if(articleCategory.getDescription()!=null) {

sql.append(", `description`=#{description}");

}if (articleCategory.getCreateUser() != null) {

sql.append(", `create_user` = #{createUser}");

}if (articleCategory.getCreateUserId() != null) {

sql.append(", `create_user_id` = #{createUserId}");

}

sql.append(", `update_time` = now()");if (articleCategory.getUpdateUser() != null) {

sql.append(", `update_user` = #{updateUser}");

}if (articleCategory.getUpdateUserId() != null) {

sql.append(", `update_user_id` = #{updateUserId}");

}

sql.append(", `version` = `version` + 1");

sql.append(" WHERE `id` = #{id} AND `version` = #{version}");returnsql.toString();

}

}

5)查询用法

Mybatis Java API mapper类:

com.dx.test.mapper.sqlprovider.ArticleMapper.java

com.dx.test.mapper.sqlprovider.ArticleCategoryMapper.java

ArticleMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleMapper {/*** 根据文章id,查询文章详情

*

*@paramid 文章id

*@return返回查询到的文章详情*/@Options(useCache= true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)

@Results(id= "articleResultWithCategory", value = { @Result(property = "id", column = "id", id = true),

@Result(property= "categoryId", column = "category_id"),

@Result(property= "articleCategory", javaType = ArticleCategory.class, one = @One(select = "com.dx.test.mapper.ArticleCategoryMapper.getById"), column = "category_id"),

@Result(property= "title", column = "title"), @Result(property = "content", column = "content"),

@Result(property= "createUser", column = "create_user"),

@Result(property= "createUserId", column = "create_user_id"),

@Result(property= "createTime", column = "create_time"),

@Result(property= "updateUser", column = "update_user"),

@Result(property= "updateUserId", column = "update_user_id"),

@Result(property= "updateTime", column = "update_time"),

@Result(property= "version", column = "version") })

@Select({"select * from article where id=#{id}"})

Article getById(@Param("id") Long id);/*** 根据文章id,查询文章详情

*

*@paramid 文章id

*@return返回查询到的文章详情*/@Options(useCache= true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)

@Results(id= "articleResultWithoutCategory", value = { @Result(property = "id", column = "id", id = true),

@Result(property= "categoryId", column = "category_id"), @Result(property = "title", column = "title"),

@Result(property= "content", column = "content"), @Result(property = "createUser", column = "create_user"),

@Result(property= "createUserId", column = "create_user_id"),

@Result(property= "createTime", column = "create_time"),

@Result(property= "updateUser", column = "update_user"),

@Result(property= "updateUserId", column = "update_user_id"),

@Result(property= "updateTime", column = "update_time"),

@Result(property= "version", column = "version") })

@Select({"select * from article where id=#{id}"})

Article getByIdWithoutCategory(@Param("id") Long id);/*** 根据条件查询文章列表

*

*@paramarticle 查询条件

*@return查询到的文章列表*/@Options(useCache= true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)

@SelectProvider(type= ArticleSqlProvider.class, method = "queryList")

@ResultMap(value= "articleResultWithoutCategory")

ListqueryList(Article article);

}

ArticleCategoryMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleCategoryMapper {/*** 根据文章分类id,查询文件分类详情

*@paramid 文章分类id

*@return查询到的文章分类详情

**/@Options(useCache= true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)

@Results(id="articleCategoryResult",value ={

@Result(property= "id",column = "id",id = true),

@Result(property= "title",column = "title"),

@Result(property= "imgSrc",column = "img_src"),

@Result(property= "description",column = "description"),

@Result(property= "createUser",column = "create_user"),

@Result(property= "createUserId",column = "create_user_id"),

@Result(property= "createTime",column = "create_time"),

@Result(property= "updateUser",column = "update_user"),

@Result(property= "updateUserId",column = "update_user_id"),

@Result(property= "updateTime",column = "update_time"),

@Result(property= "version",column = "version")

})

@Select("select * from article_category where id=#{id}")

ArticleCategory getById(Integer id);

@Options(useCache= true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)

@ResultMap(value="articleCategoryResult")

@SelectProvider(type= ArticleCategorySqlProvider.class, method = "queryList")

ListqueyrList(ArticleCategory articleCategory);

}

Mybatis Java API mapper的sql生成类:

com.dx.test.mapper.sqlprovider.ArticleSqlProvder.java

com.dx.test.mapper.sqlprovider.ArticleCategorySqlProvder.java

ArticleSqlProvder.java

packagecom.dx.test.mapper.sqlprovider;

...public classArticleSqlProvider {publicString queryList(Article article) {

StringBuilder sql=newStringBuilder();

sql.append("select * from `article_category` where 1=1 ");if(article.getId()!=null) {

sql.append(" AND `id`=#{id}");

}if (article.getCategoryId() != null) {

sql.append(" AND `category_id`=#{categoryId}");

}if (article.getTitle() != null) {

sql.append(" AND `title` like CONCAT(CONCAT('%', #{title}), '%')");

}if (article.getCreateTime() != null) {

sql.append(" AND `create_time` = #{createTime}");

}if (article.getCreateUser() != null) {

sql.append(" AND `create_user` = #{createUser}");

}if (article.getCreateUserId() != null) {

sql.append(" AND `create_user_id` = #{createUserId}");

}if (article.getUpdateTime() != null) {

sql.append(" AND `update_time` = #{updateTime}");

}if (article.getUpdateUser() != null) {

sql.append(" AND `update_user` = #{updateUser}");

}if (article.getUpdateUserId() != null) {

sql.append(" AND `update_user_id` = #{updateUserId}");

}if (article.getVersion() != null) {

sql.append(" AND `version` = #{version}");

}

sql.append(" ORDER BY `id` DESC");returnsql.toString();

}

}

ArticleCategorySqlProvder.java

packagecom.dx.test.mapper.sqlprovider;

...public classArticleCategorySqlProvider {publicString queryList(ArticleCategory articleCategory) {

StringBuilder sql=newStringBuilder();

sql.append("select * from `article_category` where 1=1 ");if(articleCategory.getId()!=null) {

sql.append(" AND `id`=#{id}");

}if (articleCategory.getTitle() != null) {

sql.append(" AND `title` like CONCAT(CONCAT('%', #{title}), '%')");

}if (articleCategory.getCreateTime() != null) {

sql.append(" AND `create_time` = #{createTime}");

}if (articleCategory.getCreateUser() != null) {

sql.append(" AND `create_user` = #{createUser}");

}if (articleCategory.getCreateUserId() != null) {

sql.append(" AND `create_user_id` = #{createUserId}");

}if (articleCategory.getUpdateTime() != null) {

sql.append(" AND `update_time` = #{updateTime}");

}if (articleCategory.getUpdateUser() != null) {

sql.append(" AND `update_user` = #{updateUser}");

}if (articleCategory.getUpdateUserId() != null) {

sql.append(" AND `update_user_id` = #{updateUserId}");

}if (articleCategory.getVersion() != null) {

sql.append(" AND `version` = #{version}");

}

sql.append(" ORDER BY `id` DESC");returnsql.toString();

}

}

6)删除用法

Mybatis Java API mapper类:

com.dx.test.mapper.sqlprovider.ArticleMapper.java

com.dx.test.mapper.sqlprovider.ArticleCategoryMapper.java

ArticleMapper.java

packagecom.dx.test.mapper;

。。。

@Mapperpublic interfaceArticleMapper {/*** 根据文章id,删除文章

*

*@paramid 文章id

*@return影响条数*/@Options(useCache= true, flushCache =Options.FlushCachePolicy.TRUE)

@Delete("delete from article where id=#{id}")intdelete(Long id);

}

ArticleCategoryMapper.java

packagecom.dx.test.mapper;

...

@Mapperpublic interfaceArticleCategoryMapper {/*** 根据文章分类id,删除文章分类

*

*@paramid 文章分类id

*@return影响条数*/@Options(useCache= true, flushCache =Options.FlushCachePolicy.TRUE)

@Delete("delete from article_category where id=#{id}")intdelete(Integer id);

}

7)入口App.java类和测试类AppTest.java

App.java

packagecom.dx.test;importjava.util.Date;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.dx.test.model.Article;importcom.dx.test.model.ArticleCategory;importcom.dx.test.service.ArticleCategoryService;importcom.dx.test.service.ArticleService;/*** Hello SpringFramework!*/

public classApp {public static voidmain(String[] args) {

@SuppressWarnings("resource")

ApplicationContext applicationContext= new ClassPathXmlApplicationContext("classpath:spring-config.xml");

ArticleService articleService= applicationContext.getBean(ArticleService.class);

ArticleCategoryService articleCategoryService= applicationContext.getBean(ArticleCategoryService.class);

ArticleCategory articleCategory=newArticleCategory();

articleCategory.setTitle("test category");

articleCategory.setImgSrc("http://im.dic/img/abd.gif");

articleCategory.setDescription("description");

articleCategory.setCreateUser("test");

articleCategory.setCreateUserId("11");

articleCategory.setCreateTime(newDate());

articleCategoryService.insert(articleCategory);

Article waitingInsertArticle=newArticle();

waitingInsertArticle.setCategoryId(articleCategory.getId());

waitingInsertArticle.setTitle("test");

waitingInsertArticle.setContent("test content");

waitingInsertArticle.setCreateUser("test");

waitingInsertArticle.setCreateUserId("11");

waitingInsertArticle.setCreateTime(newDate());int result=articleService.insert(waitingInsertArticle);

System.out.println(result);

Article article=articleService.getById(waitingInsertArticle.getId());

System.out.println(article);

}

}

AppTest.java

packagecom.dx.test;importjava.util.Date;importjava.util.List;importjava.util.Random;importorg.junit.After;importorg.junit.Assert;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importcom.dx.test.model.ArticleCategory;importcom.dx.test.service.ArticleCategoryService;/*** Unit test for simple App.*/@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration({"classpath:spring-config.xml"})public classAppTest {

@AutowiredprivateArticleCategoryService articleCategoryService;privateArticleCategory articleCategory;private final String title = "category test title";private final String titleNew = "category test title new";

@Beforepublic voidtestArticleCategoryCreate() {

ArticleCategory articleCategory= newArticleCategory();

articleCategory.setTitle(title);

articleCategory.setDescription("category description");

articleCategory.setImgSrc("http://www.test.com/img/category/img-" + new Random().nextInt(1000) + ".gif");

articleCategory.setCreateTime(newDate());

articleCategory.setCreateUser("create user");

articleCategory.setCreateUserId("user-" + new Random().nextInt(1000));int result = this.articleCategoryService.insert(articleCategory);this.articleCategory =articleCategory;

Assert.assertEquals(result,1);

}

@Testpublic voidtestSelectById() {

ArticleCategory articleCategory= this.articleCategoryService.getById(this.articleCategory.getId());

Assert.assertEquals(articleCategory.getId(),this.articleCategory.getId());

Assert.assertEquals(articleCategory.getTitle(),this.title);

}

@Testpublic voidtestQueryList() {

ArticleCategory queryArticleCategory= newArticleCategory();

queryArticleCategory.setTitle("test");

List queryResultList = this.articleCategoryService.queyrList(queryArticleCategory);

Assert.assertFalse(queryResultList.size()== 0);

}

@Testpublic voidtestUpdate() {

ArticleCategory articleCategory= this.articleCategoryService.getById(this.articleCategory.getId());

Assert.assertEquals(articleCategory.getId(),this.articleCategory.getId());

Assert.assertEquals(articleCategory.getTitle(),this.title);

articleCategory.setTitle(this.titleNew);int result=this.articleCategoryService.update(articleCategory);

Assert.assertEquals(result,1);

articleCategory= this.articleCategoryService.getById(this.articleCategory.getId());

Assert.assertEquals(articleCategory.getId(),this.articleCategory.getId());

Assert.assertEquals(articleCategory.getTitle(),this.title);

}

@Afterpublic voidtestDelete() {int result = this.articleCategoryService.delete(this.articleCategory.getId());

Assert.assertEquals(result,1);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值