1. 程式人生 > >springBoot與mybatis

springBoot與mybatis

環境jdk1.8;mysql5.7;IDEA2017

1、建立相關工程

2、引入相關的依賴

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.2</version>

</dependency>

 

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

 

3、建立application.yml並配置

spring:

datasource:

driver-class-name:com.mysql.jdbc.Driver

username:root

password:123456

url:jdbc:mysql://192.168.25.143:3306/sell?characterEncoding=utf8&useSSL=true

jpa:

show-sql:true

 

4、建立實體類,引入相關注解

packagecom.immoc.dataobject;

 

importlombok.Data;

 

importjavax.persistence.Entity;

importjavax.persistence.Id;

importjava.math.BigDecimal;

importjava.util.Date;

 

/**

*商品資訊

*/

@Entity//實體與資料庫對應

@Data//lombok註解,可省set、get等相關,提高程式碼簡潔程度

publicclassProductInfo{

@Id//其為主鍵

Private String productId;

Private String productName;

Private BigDecimal productPrice;

Private Integer productStock;

Private Stringproduct Description;

Private String productIcon;

Private Integer categoryType;

Private Date createTime;

Private Date updateTime;

 

}

5、建立sell資料庫和product_info表(sql例子)

 

SET FOREIGN_KEY_CHECKS=0;

 

-- ----------------------------

-- Table structure for product_info

-- ----------------------------

DROP TABLE IF EXISTS `product_info`;

CREATE TABLE `product_info` (

  `product_id` varchar(32) NOT NULL,

  `product_name` varchar(64) NOT NULL COMMENT '商品名稱',

  `product_price` decimal(8,2) NOT NULL COMMENT '單價',

  `product_stock` int(11) NOT NULL COMMENT '庫存',

  `product_description` varchar(64) DEFAULT NULL COMMENT '描述',

  `product_icon` varchar(512) DEFAULT NULL COMMENT '小圖',

  `product_status` tinyint(3) DEFAULT '0' COMMENT '商品狀態,0正常1下架',

  `category_type` int(11) NOT NULL COMMENT '類目編號',

  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',

  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',

  PRIMARY KEY (`product_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

6、建立mapper對映的介面

packagecom.immoc.mapper;

 

importcom.immoc.dataobject.ProductInfo;

importorg.apache.ibatis.annotations.*;

importorg.apache.ibatis.annotations.Update;

 

@Mapper

publicinterfaceProductInfoMapper{

/**

*查詢

*@paramproductId

*@return

*/

@Select("SELECTproduct_id,product_name,product_price,product_stock,product_description,product_icon,product_status,category_type,create_time,update_timeFROMproduct_infowhereproduct_id=#{productId}")

@Results({@Result(property="productId",column="product_id"),

@Result(property="productName",column="product_name"),

@Result(property="productPrice",column="product_price"),

@Result(property="productStock",column="product_stock"),

@Result(property="productDescription",column="product_description"),

@Result(property="productIcon",column="product_icon"),

@Result(property="productStatus",column="product_status"),

@Result(property="categoryType",column="category_type"),

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

})

ProductInfofindByProductId(StringproductId);

 

/**

*更新

*@paramproductInfo

*@return

*/

@Update("updateproduct_infosetproduct_id=#{productId},product_name=#{productName},product_price=#{productPrice},product_stock=#{productStock},product_description=#{productDescription},product_icon=#{productIcon},product_status=#{productStatus},category_type=#{categoryType}whereproduct_id=#{productId}")

intupdateById(ProductInfoproductInfo);

 

/**

*刪除

*@paramproductId

*@return

*/

@Delete("deletefromproduct_infowhereproduct_id=#{productId}")

intdeleteById(StringproductId);

 

/**

*插入

*@paramproductInfo

*@return

*/

@Insert("insertintoproduct_info(product_id,product_name,product_price,product_stock,product_description,product_icon,product_status,category_type)values(#{productId},#{productName},#{productPrice},#{productStock},#{productDescription},#{productIcon},#{productStatus},#{categoryType})")

intinsert(ProductInfoproductInfo);

 

}

7、測試

packagecom.immoc.mapper;

 

importcom.immoc.dataobject.ProductInfo;

importlombok.extern.slf4j.Slf4j;

importorg.junit.Assert;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.test.context.junit4.SpringRunner;

 

 

importjava.math.BigDecimal;

 

 

@Slf4j

@SpringBootTest

@RunWith(SpringRunner.class)

publicclassProductInfoMapperTest{

@Autowired

ProductInfoMapperinfoMapper;

 

@Test

publicvoidfindByProductId(){

StringproductId="1525103526600833270";

ProductInfoproductInfo=infoMapper.findByProductId(productId);

Assert.assertNotNull(productInfo);

}

 

@Test

publicvoidupdateById(){

ProductInfoproductInfo=newProductInfo();

 

productInfo.setProductId("1525103526600833270");

productInfo.setCategoryType(3);

productInfo.setProductStock(232);

productInfo.setProductStatus(1);

productInfo.setProductPrice(newBigDecimal(12123));

productInfo.setProductName("sfsd");

productInfo.setProductIcon("sfsdf");

productInfo.setProductDescription("sfs");

intupdate=infoMapper.updateById(productInfo);

Assert.assertEquals(1,update);

 

 

}

 

 

@Test

publicvoiddeleteById(){

StringproductId="1525103526600833270";

inti=infoMapper.deleteById(productId);

Assert.assertEquals(1,i);

}

 

@Test

publicvoidinsert(){

ProductInfoproductInfo=newProductInfo();

productInfo.setProductId("1525103526600833270");

productInfo.setCategoryType(3);

productInfo.setProductStock(232);

productInfo.setProductStatus(1);

productInfo.setProductPrice(newBigDecimal(12123));

productInfo.setProductName("sfsd");

productInfo.setProductIcon("sfsdf");

productInfo.setProductDescription("sfs");

inti=infoMapper.insert(productInfo);

Assert.assertEquals(1,i);

 

}

 

 

}

 

=============================================================

 

8、動態SQL

 

8.1查詢

packagecom.immoc.mapper;

 

publicclassSqlProvider{

publicStringselectProductInfo(StringproductId){

StringBuffersql=newStringBuffer("select*fromproduct_infowhere1=1");

if(productId!=null){

sql.append("andproduct_id=#{productId}");

}

 

returnsql.toString();

}

 

 

}==============

packagecom.immoc.mapper;

 

importcom.immoc.dataobject.ProductInfo;

importorg.apache.ibatis.annotations.*;

 

@Mapper

publicinterfaceProductInfoMapperProvider{

@SelectProvider(type=SqlProvider.class,method="selectProductInfo")

//@ResultMap("ProductInfoMap")

@Results({@Result(property="productId",column="product_id"),

@Result(property="productName",column="product_name"),

@Result(property="productPrice",column="product_price"),

@Result(property="productStock",column="product_stock"),

@Result(property="productDescription",column="product_description"),

@Result(property="productIcon",column="product_icon"),

@Result(property="productStatus",column="product_status"),

@Result(property="categoryType",column="category_type"),

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

})

//@ResultType(value=ProductInfo.class)

ProductInfoselectProductInfo(StringproductId);

 

}

測試

packagecom.immoc.mapper;

 

importcom.immoc.dataobject.ProductInfo;

importorg.junit.Assert;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.test.context.junit4.SpringRunner;

 

importstaticorg.junit.Assert.*;

@SpringBootTest

@RunWith(SpringRunner.class)

publicclassProductInfoMapperProviderTest{

@Autowired

ProductInfoMapperProviderinfoMapperProvider;

@Test

publicvoidselectProductInfo(){

StringproductId="1525103526600833270";

ProductInfoproductInfo=infoMapperProvider.selectProductInfo(productId);

Assert.assertEquals(productId,productInfo.getProductId());

}

}

====================

二、springboot與mybatis整合帶xml檔案

1、環境 IDEA;jdk1.8;mysql5.7;

2、建立相關工程

   2.1引入依賴pom檔案為

<?xmlversion="1.0"encoding="UTF-8"?>

<projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

 

<groupId>com.example</groupId>

<artifactId>sell-weixin</artifactId>

<version>0.0.1-SNAPSHOT</version>

<modules>

<module>../ganerate-code</module>

</modules>

<packaging>pom</packaging>

 

<name>sell-weixin</name>

<description>DemoprojectforSpringBoot</description>

 

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.0.1.RELEASE</version>

<relativePath/><!--lookupparentfromrepository-->

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

<!--google相關json依賴-->

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

</dependency>

<!--熱部署使用jar包-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<version>2.0.1.RELEASE</version>

<optional>true</optional>

<!--optional=true,依賴不會傳遞,該專案依賴devtools;之後依賴該專案的專案如果想要使用devtools,需要重新引入-->

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-freemarker</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.2</version>

</dependency>

 

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

 

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

 

 

</project>

 

   2.2配置檔案為

spring:

datasource:

driver-class-name:com.mysql.jdbc.Driver

username:root

password:123456

url:jdbc:mysql://192.168.25.143:3306/sell?characterEncoding=utf8&useSSL=true

jpa:

show-sql:true

#ldatabase-platform:org.hibernate.dialect.MySQL5Dialect

 

#載入mybatis配置檔案mybatis:

mybatis:

mapper-locations:classpath*:mapper/*Mapper.xml

#type-aliases-package:cn.itcast.domain

#資料來源

3、mapper介面

 

Package com.immoc.mapper;

 

 

 

 

Import com.immoc.dataobject.ProductInfo;

Import org.apache.ibatis.annotations.Mapper;

@Mapper

Public interface ProductInfoMapper{

ProductInfo selectByPrimaryKey (StringproductId);

}

4、xml對映

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mappernamespace="com.immoc.mapper.ProductInfoMapper"><!--介面路徑-->

<resultMapid="BaseResultMap"type="com.immoc.dataobject.ProductInfo"><!--實體類的路徑--><idcolumn="product_id"jdbcType="VARCHAR"property="productId"/>

<resultcolumn="product_name"jdbcType="VARCHAR"property="productName"/>

<resultcolumn="product_price"jdbcType="DECIMAL"property="productPrice"/>

<resultcolumn="product_stock"jdbcType="INTEGER"property="productStock"/>

<resultcolumn="product_description"jdbcType="VARCHAR"property="productDescription"/>

<resultcolumn="product_icon"jdbcType="VARCHAR"property="productIcon"/>

<resultcolumn="product_status"jdbcType="TINYINT"property="productStatus"/>

<resultcolumn="category_type"jdbcType="INTEGER"property="categoryType"/>

<resultcolumn="create_time"jdbcType="TIMESTAMP"property="createTime"/>

<resultcolumn="update_time"jdbcType="TIMESTAMP"property="updateTime"/>

</resultMap>

<selectid="selectByPrimaryKey"parameterType="java.lang.String"resultMap="BaseResultMap">

select

*

fromproduct_info

whereproduct_id=#{productId,jdbcType=VARCHAR}

</select>

</mapper>

 

5、測試

packagecom.immoc.mapper;

 

importcom.immoc.dataobject.ProductInfo;

importlombok.extern.slf4j.Slf4j;

importorg.junit.Assert;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.test.context.junit4.SpringRunner;

 

 

importjava.math.BigDecimal;

 

 

@Slf4j

@SpringBootTest

@RunWith(SpringRunner.class)

publicclassProductInfoMapperTest{

@Autowired

ProductInfoMapperinfoMapper;

 

@Test

publicvoidfindByProductId(){

StringproductId="1525103526600833270";

ProductInfoinfo=infoMapper.selectByPrimaryKey(productId);

System.out.println(1);

System.out.println(info);

Assert.assertNotNull(info);

}

 

}