springboot2.0 快速集成mybaties

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ljk126wy/article/details/83141118

通过mybaties官方网址:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ 我们可以发现mybaties 为springboot 提供了2个版本的demo: 1 注解方式  2 xml方式

我们要先讲github的代码拷贝下来 https://github.com/mybatis/spring-boot-starter

 

1 注解的方式

下图就是官方给的列子,无需添加任何配置就可以使用了。根据这个里子我们可以大致知道如何通过注解来进行定义查询方法。但是这个案例就一个查询方法 敢不敢在多写几个啊!。你们也太懒了吧!

哎!我们还是去mybaties的官网继续寻找答案吧 http://www.mybatis.org/mybatis-3/java-api.html

 看完后有点像写点demo的冲动啊! come on !

这里我们开始自己写注解版的增删改查, 我们定义一个商品类 包含的成员属性有 商品id 商品名称 商品价格 商品简介。在开始之前千万别忘了引入mybaties start依赖和mysql的依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
package cn.lijunkui.mybaties.domain;
/**
 *  商品的实体类
 * @author lijunkui
 *
 */
public class Product {
	private Long id;
	private String productName;
	private Double price;
	private String productBrief;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public String getProductBrief() {
		return productBrief;
	}
	public void setProductBrief(String productBrief) {
		this.productBrief = productBrief;
	}
}

 添加数据库的表前需要我们定义数据库配置文件信息。

server:
  servlet:
    context-path: /learn
  port: 8080
  

spring:
  banner:
    charset: UTF-8 # Banner file encoding.
    #location: classpath:banner.txt # Banner text resource location.
    image:
      #location: classpath:banner.gif # Banner image file location (jpg or png can also be used).
      width: 10 # Width of the banner image in chars.
      height: 10 # Height of the banner image in chars (default based on image height).
      margin: 2 # Left hand image margin in chars.
      invert: false # Whether images should be inverted for dark terminal themes.
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybaties?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root

测试建库建表sql 

/*
SQLyog Ultimate v9.62 
MySQL - 5.5.27 : Database - mybaties
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybaties` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybaties`;

/*Table structure for table `product` */

CREATE TABLE `product` (
  `id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '商品id',
  `product_Name` varchar(25) DEFAULT NULL COMMENT '商品名称',
  `price` decimal(8,3) DEFAULT NULL COMMENT '价格',
  `product_Brief` varchar(125) DEFAULT NULL COMMENT '商品简介',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

/*Data for the table `product` */

insert  into `product`(`id`,`product_Name`,`price`,`product_Brief`) values (1,'苹果','20.000','好吃的苹果,红富士大苹果');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

定义mapper

package cn.lijunkui.mybaties.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import cn.lijunkui.mybaties.domain.Product;

@Mapper
public interface ProductMapper {
	
	@Results(id="product" ,value= { 
			@Result(property = "id", column = "id", id = true),
			@Result(property = "productName", column = "product_Name"),
			@Result(property = "price", column = "price"),
			@Result(property = "productBrief", column = "product_Brief")
	})
	@Select("select * from product where id = #{id}")
	public Product findById(@Param("id") Long id);
}

 添加测试用例:

package cn.lijunkui.mybaties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.lijunkui.mybaties.domain.Product;
import cn.lijunkui.mybaties.mapper.ProductMapper;
import junit.framework.Assert;
/**
 * @author lijunkui
 *
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProductMapperTest {
	
	@Autowired
	private ProductMapper productMapper;
	
	@SuppressWarnings("deprecation")
	@Test
	public void findById() {
		Product product = productMapper.findById(1l);
		Assert.assertNotNull(product);
	}
	
}

测试结果:

 

继续完善我们的增删改查

package cn.lijunkui.mybaties.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import cn.lijunkui.mybaties.domain.Product;

@Mapper
public interface ProductMapper {
	/**
	 * 根据id进行商品的查询
	 * @param id
	 * @return Product
	 */
	@Results(id="product" ,value= { 
			@Result(property = "id", column = "id", id = true),
			@Result(property = "productName", column = "product_Name"),
			@Result(property = "price", column = "price"),
			@Result(property = "productBrief", column = "product_Brief")
	})
	@Select("select * from product where id = #{id}")
	public Product findById(@Param("id") Long id);
	/**
	 * 条件查询
	 * @param product
	 * @return
	 */
	
	@SelectProvider(type = ProductProvider.class, method = "findByCondition")
	public List<Product> findByCondition(Product product);
	/**
	 * 添加商品
	 * @param product
	 * @return Long 表示影响的行数
	 */
	@Insert("insert into product (product_Name, price,product_Brief) values(#{productName}, #{price}, #{productBrief})")
	@Options(useGeneratedKeys=true,keyProperty="id")
	@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = long.class)
	public Long insert(Product product);
	
	/**
	 * 修改商品
	 * @param product
	 */
	@Update("update product set product_Name=#{productName} , price= #{price} , product_Brief = #{productBrief} where  id=#{id}")
	public void update(Product product);
	/**
	 * 动态修改商品
	 * @param product
	 */
	@UpdateProvider(type = ProductProvider.class, method = "updateDynamic")
	public void updateDynamic(Product product);
	/**
	 * 删除商品
	 * @param id
	 */
	 @Delete("delete from product where id=#{id}")
	 public void deleteById(long id);
	
}
package cn.lijunkui.mybaties.mapper;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import cn.lijunkui.mybaties.domain.Product;

public class ProductProvider {
	   public String updateDynamic(Product product) {  
		   	return new SQL() {{
        	   UPDATE("product");
        	   if (!StringUtils.isEmpty(product.getProductName())) {
        		   SET("product_Name = #{productName}");
        	   }
        	   if (product.getPrice()!=null) {
        		   SET("price = #{price}");
        	   }
        	   if(!StringUtils.isEmpty(product.getProductBrief()))
        		   SET("product_Brief = #{productBrief}");
        	   }}.toString();
       }
	   
	   public String findByCondition(Product product) {
		   return new SQL() {{
			   SELECT("id,product_Name as productName ,price,product_Brief as productBrief");
			   FROM("product");
			   if (!StringUtils.isEmpty(product.getProductName())) {
				   WHERE("product_Name like CONCAT('%',#{productName},'%')");
        	   }
			   if (product.getPrice()!=null) {
				   WHERE("price = #{price} ");
        	   }
        	  
		   }}.toString();
	   }
       
}
package cn.lijunkui.mybaties;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.lijunkui.mybaties.domain.Product;
import cn.lijunkui.mybaties.mapper.ProductMapper;
import junit.framework.Assert;
/**
 * @author lijunkui
 *
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProductMapperTest {
	
	@Autowired
	private ProductMapper productMapper;
	
	@SuppressWarnings("deprecation")
	@Test
	public void findById() {
		Product product = productMapper.findById(1l);
		Assert.assertNotNull(product);
	}
	@SuppressWarnings("deprecation")
	@Test
	public void findByCondition() {
		Product product = new Product();
		product.setProductName("蕉");
		List<Product> findByCondition = productMapper.findByCondition(product);
		Assert.assertTrue(findByCondition.size()>0);
	}
	@SuppressWarnings("deprecation")
	@Test
	public void insert() {
		Product product = new Product();
		product.setProductName("香蕉");
		product.setPrice(45d);
		product.setProductBrief("好吃的香蕉!");
		Long insert = productMapper.insert(product);
		Assert.assertTrue(insert > 0 );
	}
	@Test
	public void update() {
		Product product = new Product();
		product.setId(3l);
		product.setProductName("香蕉3");
		product.setPrice(45d);
		product.setProductBrief("好吃的香蕉!");
		productMapper.update(product);
	}
	
	@Test
	public void updateDynamic() {
		Product product = new Product();
		product.setId(4l);
		product.setProductName("香蕉4");
		productMapper.updateDynamic(product);
	}
	@Test
	public void deleteById() {
		productMapper.deleteById(4l);
	}
}

2 xml方式

查看官方demo 我们需要配置一个mybatis-config.xml 然后定义Mapper类 和其映射绑定的mapper xml 就ok 下面是官方代码

同时在配置文件中配置 mybatis-config.xml

定义Mapper

 

阅读完毕 我们开始我们xml讲解自己写一遍。 相信使用过mybaties同学们对xml的方式一定不陌生。 我们这里就就写一个查询方法进行测试。

测试建表sql 和测试数据

CREATE TABLE `hotel` (
  `id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '旅馆id',
  `city` varchar(125) DEFAULT NULL COMMENT '城市',
  `name` varchar(125) DEFAULT NULL COMMENT '旅馆名称',
  `address` varchar(256) DEFAULT NULL COMMENT '旅馆地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

INSERT INTO `mybaties`.`hotel`(`id`,`city`,`name`,`address`) VALUES ( '1','北京','汉庭','朝阳区富明路112号');

创建Hotle 实体 其中包含  旅馆id 城市 旅馆名称 旅馆地址 成员属性

package cn.lijunkui.mybaties.domain;

public class Hotel {
	private Long id;
	private String city;
	private String name;
	private String address;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

 创建 Hotel 的Mapper类

package cn.lijunkui.mybaties.mapper;

import org.apache.ibatis.annotations.Mapper;

import cn.lijunkui.mybaties.domain.Hotel;



@Mapper
public interface HotelMapper {
	Hotel selectByCityId(long id);
}

创建Mapper类映射的xml  namespace 是 HotelMapper 的包路径地址

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2015-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lijunkui.mybaties.mapper.HotelMapper">
    <select id="selectByCityId" resultType="Hotel">
        select * from hotel where id = #{id}
    </select>
</mapper>

 创建mybatis-config.xml 并且设置HotelMapper.xml 

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2015-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="cn.lijunkui.mybaties.domain"/>
    </typeAliases>
    <mappers>
        <mapper resource="mybaties/mapper/HotelMapper.xml"/>
    </mappers>
</configuration>

配置文件目录地址如下图:

编写测试用例:

package cn.lijunkui.mybaties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.lijunkui.mybaties.domain.Hotel;
import cn.lijunkui.mybaties.mapper.HotelMapper;
import junit.framework.Assert;
@SpringBootTest
@RunWith(SpringRunner.class)
public class HotelMapperTest {
	
	@Autowired
	private HotelMapper hotelMapper;
	
	@SuppressWarnings("deprecation")
	@Test
	public void selectByCityId() {
		Hotel result = hotelMapper.selectByCityId(1l);
		Assert.assertNotNull(result);
	}
}

demo的 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>cn.lijunkui</groupId>
	<artifactId>springbootlearn</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springbootlearn</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
		   <groupId>org.springframework.boot</groupId>
		   <artifactId>spring-boot-starter-quartz</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>1.1.1</version>
		</dependency>
		     <dependency>
        		<groupId>mysql</groupId>
        		<artifactId>mysql-connector-java</artifactId>
    		</dependency>
     		<dependency>
        		<groupId>org.springframework.boot</groupId>
       		 <artifactId>spring-boot-devtools</artifactId>
       		 <optional>true</optional>
    		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

3 demo版本说明:

开发工具:Spring Tool Suite (STS)

springboot版本:2.0.5.RELEASE

jdk版本:1.8.0_144

mybatise start 版本:1.1.1

猜你喜欢

转载自blog.csdn.net/ljk126wy/article/details/83141118