1. 程式人生 > >springboot 學習-整合mybaties

springboot 學習-整合mybaties

1 註解的方式

下圖就是官方給的列子,無需新增任何配置就可以使用了。根據這個裡子我們可以大致知道如何通過註解來進行定義查詢方法。但是這個案例就一個查詢方法 敢不敢在多寫幾個啊!。你們也太懶了吧!

 看完後有點像寫點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 @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @[email protected]@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 [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40111 SET [email protected]_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版本說明:

springboot版本:2.0.5.RELEASE

jdk版本:1.8.0_144

mybatise start 版本:1.1.1