SPRINGBOOT2.X微应用基础版
环境说明
IDE:Spring Tool Suite 4 。
JDK:1.8
spring boot版本:2.0.6.RELEASE
MAVEN:构建多工程
持久层: MYBATIS mybatis-spring-boot-starter 1.3.2
工程结构
通过MAVEN构建多工程:
主工程 : BZQ-4Spring-B2B2C
消费者 : BZQ-B2B2C-ADDRESS-CONSUMER
生产者:BZQ-B2B2C-ADDRESS-PROVIDER
工具者: BZQ-B2B2C-COMMON
基础API: BZQ-B2B2C-ADDRESS-API;
MAVEN配置
主工程 : BZQ-4Spring-B2B2C:
<?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>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-API</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
</project>
BZQ-B2B2C-ADDRESS-CONSUMER:
<?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>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-CONSUMER</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<name>BZQ-B2B2C-ADDRESS-CONSUMER</name>
<description>BZQ B2B2C ADDRESS CONSUMER</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<modules>
<!-- -->
</modules>
<dependencies>
<!-- 商品API-->
<dependency>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-API</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-PROVIDER</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.bzqb2b2c.common</groupId>
<artifactId>BZQ-B2B2C-COMMON</artifactId>
<version>1.0-SNAPSHOT</version>
</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>
<!-- SpringBoot2.X 使用 devtools 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- 阿里巴巴的Druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!-- log4j 1.2.17 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<!--dubbo 依赖 开始
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
-->
<!--springboot集成dubbo的依赖 开始 -->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.12</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>
<!--springboot集成dubbo的依赖 结束 -->
<!--dubbo 依赖 结束 -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
BZQ-B2B2C-ADDRESS-PROVIDER:
<?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>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-PROVIDER</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>BZQ-B2B2C-ADDRESS-PROVIDER</name>
<description>BZQ B2B2C ADDRESS PROVIDER</description>
<!--
<parent>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-CONSUMER</artifactId>
<version>1.0-SNAPSHOT</version>
</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>
<!-- 商品API-->
<dependency>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-API</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.bzqb2b2c.common</groupId>
<artifactId>BZQ-B2B2C-COMMON</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--springboot集成dubbo的依赖 begin -->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.12</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>
<!--springboot集成dubbo的依赖 end -->
</dependencies>
</project>
BZQ-B2B2C-COMMON:
<?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>com.bzqb2b2c.common</groupId>
<artifactId>BZQ-B2B2C-COMMON</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
</project>
BZQ-B2B2C-ADDRESS-API:
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties></kbd>
MaVEN配置说明
依赖SPRING2工程:
org.springframework.boot spring-boot-starter-parent 2.0.6.RELEASE #### MAVEN引用其它工程: <dependencies>
<!-- 商品API-->
<dependency>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-API</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.bzqb2b2c.address</groupId>
<artifactId>BZQ-B2B2C-ADDRESS-PROVIDER</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.bzqb2b2c.common</groupId>
<artifactId>BZQ-B2B2C-COMMON</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
SPRINGBOOT2配置说明
*配置方式
采用yml配置文件
BZQ-B2B2C-ADDRESS-CONSUMER
src
main
resources
application.yml
**application.yml
这个文件很简单,它只是引用各独立配置文件,个人喜欢这样管理
## include
spring:
profiles:
include: dubbo,mvc,mybatis,jdbc,log4j
MyBatis的相关配置
这个yml文件,一定要注意它的格式,每个:号都有个空格(TMD)
## MyBatis的相关配置
mybatis:
# 映射文件位置
mapper-locations: classpath:com/soukong/center/address/mapper/*.xml
# 别名扫描包
type-aliases-package: com.soukong.center.address.entity
# 输出SQL执行语句
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true ###开启驼峰命名
## pagehelper分页相关配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
returnPageInfo: check
MVC,说明商品,部署目录名
## 服务器端口号
spring:
mvc:
view:
prefix: /
suffix: .html
resources:
static-locations: /resources/,/static/
server:
port: 89
servlet:
context-path: /address
关于数据库参数的相关配置
## 关于数据库参数的相关配置
spring:
datasource:
name: mysql_test
type: com.alibaba.druid.pool.DruidDataSource
#druid相关配置
druid:
#监控统计拦截的filters
filters: stat
driver-class-name: com.mysql.jdbc.Driver
#基本属性
url: jdbc:mysql://localhost:3306/ware-center?characterEncoding=utf-8
username: root
password: 123456
#配置初始化大小/最小/最大
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 600000
#间隔多久进行一次检测,检测需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#一个连接在池中最小生存的时间
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
- Dubbo 服务提供者配置.
## Dubbo 服务提供者配置
spring:
dubbo:
appname: sample-base-service-provider
registry: zookeeper://localhost:2181
protocol: dubbo
port: 20880
- log4j
## log4j
logging:
level:
com.soukong.center: debug,info
ZooKeeper server
基本不要什么配置,注意环境中的端口要统一!
官网链接: 自己去下载.
图片: ![Alt](https://av
SPRINGBOOT2项目启动
SPRING启动有很多方式,我这里用Application.main()方式
// 启动类,它一定要放在最高的目录位置,我所有的东西放在com.soukong.center.address的子目录下,它就放com.soukong.center.address,如果位置不对,会完死你。
package com.soukong.center.address;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
/**
* @作者:鲍忠启
* @描述:SpringBoot主类-启动类 com.soukong.center.manage.dao
*/
@EnableDubbo //启动DUBBO
@SpringBootApplication
@ImportResource({"classpath:appCtx-provider.xml"}) //这个是配置Dubbo用的。
@MapperScan({"com.soukong.center.address.dao" }) // 扫描你的DAO类
//@MapperScan("com.chengcheng.goods.dao.sys")
public class StartAddressApplication {
public static void main(String[] args) {
SpringApplication.run(StartAddressApplication.class, args);
}
}
SPRINGBOOT2简单版本的启动类
package com.soukong.center.address;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
/**
* @作者:BZQ
* @描述:SpringBoot主类-启动类 com.soukong.center.manage.dao
*/
@SpringBootApplication
@MapperScan({"com.soukong.center.address.dao" })
public class StartAddressApplication {
public static void main(String[] args) {
SpringApplication.run(StartAddressApplication.class, args);
}
}
Spring Boot 推荐目录结构
(1)代码层的结构
根目录:com.springboot
1.工程启动类(ApplicationServer.java)置于com.springboot.build包下
2.实体类(domain)置于com.springboot.domain
3.数据访问层(Dao)置于com.springboot.repository
4.数据服务层(Service)置于com,springboot.service,数据服务的实现接口(serviceImpl)至于com.springboot.service.impl
5.前端控制器(Controller)置于com.springboot.controller
6.工具类(utils)置于com.springboot.utils
7.常量接口类(constant)置于com.springboot.constant
8.配置信息类(config)置于com.springboot.config
9.数据传输类(vo)置于com.springboot.vo
(2)资源文件的结构
根目录:src/main/resources
1.配置文件(.properties/.json等)置于config文件夹下
2.国际化(i18n))置于i18n文件夹下
3.spring.xml置于META-INF/spring文件夹下
4.页面以及js/css/image等置于static文件夹下的各自文件下
src/main/java:
主程序入口 Application,可以通过直接运行该类来 启动 Spring Boot应用
src/main/resources:
配置目录,该目录用来存放应用的一些配置信息,比如应用名、服务端口、数据库配置等。由于我们应用了Web模块,因此产生了 static目录与templates
目录,前者用于存放静态资源,如图片、CSS、JavaScript等;后者用于存放Web页面的模板文件。
src/test:
单元测试目录,生成的 ApplicationTests 通过 JUnit4实现,可以直接用运行 Spring Boot应用的测试。
application.properties/application.yml
用于存放程序的各种依赖模块的配置信息,比如 服务端口,数据库连接配置等。。。
控制层代码(controller)
BZQ-B2B2C-ADDRESS-CONSUMER工程。
package com.soukong.center.address.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
import com.soukong.center.common.utils.PageUtils;
import com.soukong.center.address.dubbo.service.AreaDubboService;
import com.soukong.center.address.entity.AreaEntity;
import com.soukong.center.address.service.AreaService;
import com.soukong.center.common.utils.R;
import com.soukong.center.common.utils.RRException;
/**
* 地区码表
*
* @author 鲍忠启
* @date 2019-02-27 15:50:24
*/
@Controller
@RequestMapping("/area")
public class AreaController {
@Autowired // 这个标签下面一定要有内容,不然坑死你
private AreaDubboService areaService;
/**
* 列表
*/
@ResponseBody
@RequestMapping("/list")
public R list(Integer page, Integer limit){
Map<String, Object> map = new HashMap<>();
map.put("offset", (page - 1) * limit);
map.put("limit", limit);
//查询列表数据
List<AreaEntity> areaList = areaService.queryList(map);
int total = areaService.queryTotal(map);
PageUtils pageUtil = new PageUtils(areaList, total, limit, page);
return R.ok().put("page", pageUtil);
}
/**
*/
@ResponseBody
@RequestMapping("/info/{areaid}")
public R info(@PathVariable("areaid") Long areaid){
AreaEntity area = (AreaEntity)areaService.queryObject(areaid);
return R.ok().put("area", area);
}
/**
*/
@ResponseBody
@RequestMapping("/save")
public R save(@RequestBody AreaEntity area){
areaService.save(area);
return R.ok();
}
/**
*/
@ResponseBody
@RequestMapping("/update")
public R update(@RequestBody AreaEntity area){
areaService.update(area);
return R.ok();
}
}
服务层代码(DUBBO)
-
BZQ-B2B2C-ADDRESS-PROVIDER,这里我贴出DUBBO方式代码
- `package com.soukong.center.address.dubbo.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.soukong.center.address.dubbo.service.AreaDubboService;
import com.soukong.center.address.entity.AreaEntity;
import com.soukong.center.address.service.AreaService;
/**
- 地区Dubbo
- @作者:鲍忠启
*/
@Service(“areaDubboService”)
public class AreaDubboServiceImpl implements AreaDubboService{
@Autowired
private AreaService areaService;
/** 查询用户地址 */
public AreaEntity queryObject(Long addressId) {
return areaService.queryObject(addressId);
}
/** 分页查询地址 */
public List<AreaEntity> queryList(Map<String, Object> map){
return areaService.queryList(map);
}
/** 分页查询地址 */
public int queryTotal(Map<String, Object> map) {
return areaService.queryTotal(map);
}
/** 新增 */
public Long save(AreaEntity userAddressInfo) {
areaService.save(userAddressInfo);
return 1L;
}
/** 修改 */
public void update(AreaEntity userAddressInfo) {
areaService.update(userAddressInfo);
}
/** 新增+修改(合并使用) */
public Long edit(AreaEntity userAddressInfo) {
return 1L;
}
/** 按地址ID删除地址 */
public void delete(Long addressId) {
areaService.delete(addressId);
}
}
`
DUBBO接口定义
BZQ-B2B2C-ADDRESS-API工程。[^2]
package com.soukong.center.address.dubbo.service;
import java.util.List;
import java.util.Map;
import com.soukong.center.address.entity.AreaEntity;
//接口
public interface AreaDubboService {
/** 查询用户地址 */
public AreaEntity queryObject(Long addressId);
/** 分页查询地址 */
public List<AreaEntity> queryList(Map<String, Object> map);
/** 分页查询地址 */
public int queryTotal(Map<String, Object> map);
/** 新增 */
public Long save(AreaEntity userAddressInfo);
/** 修改 */
public void update(AreaEntity userAddressInfo);
/** 新增+修改(合并使用) */
public Long edit(AreaEntity userAddressInfo);
/** 按地址ID删除地址 */
public void delete(Long addressId);
}
通用服务层代码
- 接口
package com.soukong.center.address.service;
import com.soukong.center.address.entity.AreaEntity;
import java.util.List;
import java.util.Map;
/**
* 地区码表
* @作者:鲍忠启
* @date 2018-11-07 15:50:24
*/
public interface AreaService {
AreaEntity queryObject(Long areaid);
List<AreaEntity> queryList(Map<String, Object> map);
int queryTotal(Map<String, Object> map);
void save(AreaEntity area);
void update(AreaEntity area);
void delete(Long areaid);
void deleteBatch(Long[] areaids);
void deleteByLogicId(Long areaid);
void deleteByLogicList(Long[] areaids);
public List<AreaEntity> getPccList(Map<String,Object> map) ;
}
- 实现类
package com.soukong.center.address.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.soukong.center.address.dao.AreaDao;
import com.soukong.center.address.entity.AreaEntity;
import com.soukong.center.address.service.AreaService;
/**
* 地区码表
* @author 鲍忠启
* @date 2018-11-07 15:50:24
*/
@Service("areaService")
public class AreaServiceImpl implements AreaService {
@Autowired
private AreaDao areaDao;
public AreaEntity queryObject(Long areaid){
return areaDao.queryObject(areaid);
}
public List<AreaEntity> queryList(Map<String, Object> map){
return areaDao.queryList(map);
}
public int queryTotal(Map<String, Object> map){
return areaDao.queryTotal(map);
}
public void save(AreaEntity area){
areaDao.save(area);
}
public void update(AreaEntity area){
areaDao.update(area);
}
public void delete(Long areaid){
areaDao.delete(areaid);
}
public void deleteBatch(Long[] areaids){
areaDao.deleteBatch(areaids);
}
public void deleteByLogicId(Long areaid){
areaDao.deleteByLogicId(areaid);
}
public void deleteByLogicList(Long[] areaids){
areaDao.deleteByLogicList(areaids);
}
public List<AreaEntity> getPccList(Map<String,Object> map) {
return areaDao.getPccList(map);
}
}
SPRINGBOOT2持久层
- 接口
package com.soukong.center.address.dao;
import com.soukong.center.address.entity.AreaEntity;
import java.util.Map;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
/**
* 地区码表
* @作者:鲍忠启
* @date 2018-11-07 15:50:24
*/
public interface AreaDao extends BaseDao<AreaEntity> {
public List<AreaEntity> getPccList(Map<String,Object> map) ;
}
- MAPPER文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soukong.center.address.dao.AreaDao">
<select id="queryObject" resultType="com.soukong.center.address.entity.AreaEntity">
select * from tb_area where del_flag=0 and areaId = #{value}
</select>
<select id="queryList" resultType="com.soukong.center.address.entity.AreaEntity">
select * from tb_area where del_flag=0
<if test="areacode !=null">
and areaCode = #{areacode}
</if>
<if test="areaname !=null">
and areaName = #{areaname}
</if>
<if test="areanameLike !=null">
and areaName like CONCAT(#{areanameLike},'%')
</if>
<if test="level !=null">
and level = #{level}
</if>
<if test="parentname !=null ">
and parentCode in (select areaCode from tb_area where del_flag=0 and areaName=#{parentname})
</if>
<if test="citycode !=null">
and cityCode = #{citycode}
</if>
<if test="center !=null">
and center = #{center}
</if>
<if test="parentcode !=null">
and parentCode = #{parentcode}
</if>
<if test="createTime !=null">
and create_time = #{createTime}
</if>
<if test="updateTime !=null">
and update_time = #{updateTime}
</if>
<if test="delFlag !=null">
and del_flag = #{delFlag}
</if>
<if test="opId !=null">
and op_id = #{opId}
</if>
<if test="version !=null">
and version = #{version}
</if>
<if test="offset != null and limit != null">
limit #{offset}, #{limit}
</if>
</select>
<select id="queryTotal" resultType="int">
select count(*) from tb_area where del_flag=0
<if test="areacode !=null">
and areaCode = #{areacode}
</if>
<if test="areaname !=null">
and areaName = #{areaname}
</if>
<if test="areanameLike !=null">
and areaName like CONCAT(#{areanameLike},'%')
</if>
<if test="level !=null">
and level = #{level}
</if>
<if test="citycode !=null">
and cityCode = #{citycode}
</if>
<if test="center !=null">
and center = #{center}
</if>
<if test="parentcode !=null">
and parentCode = #{parentcode}
</if>
<if test="createTime !=null">
and create_time = #{createTime}
</if>
<if test="updateTime !=null">
and update_time = #{updateTime}
</if>
<if test="delFlag !=null">
and del_flag = #{delFlag}
</if>
<if test="opId !=null">
and op_id = #{opId}
</if>
<if test="version !=null">
and version = #{version}
</if>
</select>
<insert id="save" parameterType="com.soukong.center.address.entity.AreaEntity" useGeneratedKeys="true" keyProperty="areaid">
insert into tb_area
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="areacode!= null" >
areaCode,
</if>
<if test="areaname!= null" >
areaName,
</if>
<if test="level!= null" >
level,
</if>
<if test="citycode!= null" >
cityCode,
</if>
<if test="center!= null" >
center,
</if>
<if test="parentcode!= null" >
parentCode,
</if>
<if test="createTime!= null" >
create_time,
</if>
<if test="updateTime!= null" >
update_time,
</if>
<if test="delFlag!= null" >
del_flag,
</if>
<if test="opId!= null" >
op_id,
</if>
<if test="version!= null" >
version,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="areacode != null" >
#{areacode},
</if>
<if test="areaname != null" >
#{areaname},
</if>
<if test="level != null" >
#{level},
</if>
<if test="citycode != null" >
#{citycode},
</if>
<if test="center != null" >
#{center},
</if>
<if test="parentcode != null" >
#{parentcode},
</if>
<if test="createTime != null" >
#{createTime},
</if>
<if test="updateTime != null" >
#{updateTime},
</if>
<if test="delFlag != null" >
#{delFlag},
</if>
<if test="opId != null" >
#{opId},
</if>
<if test="version != null" >
#{version},
</if>
</trim>
</insert>
<update id="update" parameterType="com.soukong.center.address.entity.AreaEntity">
update tb_area
<set>
<if test="areacode != null">`areaCode` = #{areacode}, </if>
<if test="areaname != null">`areaName` = #{areaname}, </if>
<if test="level != null">`level` = #{level}, </if>
<if test="citycode != null">`cityCode` = #{citycode}, </if>
<if test="center != null">`center` = #{center}, </if>
<if test="parentcode != null">`parentCode` = #{parentcode}, </if>
<if test="createTime != null">`create_time` = #{createTime}, </if>
<if test="updateTime != null">`update_time` = #{updateTime}, </if>
<if test="delFlag != null">`del_flag` = #{delFlag}, </if>
<if test="opId != null">`op_id` = #{opId}, </if>
<if test="version != null">`version` = #{version}</if>
</set>
where areaId = #{areaid}
</update>
<delete id="delete">
delete from tb_area where areaId = #{value}
</delete>
<delete id="deleteBatch">
delete from tb_area where areaId in
<foreach item="areaid" collection="array" open="(" separator="," close=")">
#{areaid}
</foreach>
</delete>
<update id="deleteByLogicId">
update tb_area set del_flag=1 where 1=1 and areaId = #{value}
</update>
<update id="deleteByLogicList">
update tb_area set del_flag=1 where 1=1 and areaId in
<foreach item="areaid" collection="array" open="(" separator="," close=")">
#{areaid}
</foreach>
</update>
<select id="getPccList" resultType="com.soukong.center.address.entity.AreaEntity" parameterType="java.util.Map" >
SELECT t1.areaCode, t1.areaName ,t1.level FROM tb_area t1 where t1.areaCode = #{provinceCode}
UNION
SELECT t2.areaCode, t2.areaName ,t2.level FROM tb_area t2 where t2.areaCode = #{cityCode}
UNION
SELECT t3.areaCode, t3.areaName ,t3.level FROM tb_area t3 where t3.areaCode = #{countyCode}
</select>
</mapper>
SPRINGBOOT2持久层有很多实现方式,我这里用mybatis.
MYBATIS说明
pom.xml文件中需要加入
- 依赖
<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>
<!-- 阿里巴巴的Druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>```
- application-mybatis.yml
##springboot2 MyBatis的相关配置
mybatis:
# 映射文件位置
mapper-locations: classpath:com/soukong/center/address/mapper/*.xml ### SQL文件目录,可以用通配符方式
# 别名扫描包
type-aliases-package: com.soukong.center.address.entity ### 实体类目录
# 输出SQL执行语句
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true ###开启驼峰命名
## pagehelper分页相关配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
returnPageInfo: check
SPRINGBOOT2配置DUBBO
- 启动,要启动消费者、生产者哦
package com.soukong.center.manage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
/** 消费者
* @作者:鲍忠启
* @描述:SpringBoot主类-启动类 com.soukong.center.manage.dao
*/
@EnableDubbo
//@EnableDubboConfiguration
@SpringBootApplication
@ImportResource({"classpath:appCtx-consumer.xml"})
//@DubboComponentScan(basePackages = "com.soukong.center.address.dubbo.service")
@MapperScan({"com.soukong.center.manage.mapper","com.soukong.center.manage.mapper.sys","com.soukong.center.manage.dao"})
//@MapperScan("com.chengcheng.goods.dao.sys")
public class StartManageApplication {
public static void main(String[] args) {
SpringApplication.run(StartManageApplication.class, args);
}
}
//package com.soukong.center.address;
package com.soukong.center.address;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
/** 生产者
* @作者:鲍忠启
* @描述:SpringBoot主类-启动类 com.soukong.center.manage.dao
*/
@EnableDubbo
@SpringBootApplication
@ImportResource({"classpath:appCtx-provider.xml"})
@MapperScan({"com.soukong.center.address.dao" })
//@MapperScan("com.chengcheng.goods.dao.sys")
public class StartAddressApplication {
public static void main(String[] args) {
SpringApplication.run(StartAddressApplication.class, args);
}
}
- 配置 pom.xml 文件中需要有:
<!--springboot集成dubbo的依赖 开始 -->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.12</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>
<!--springboot集成dubbo的依赖 结束 -->
- DUBBO配置,我采用XML方式,和以前的一样,有两部分哦,我都放在/resouces/appCtx-provider.xml
注册方
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"
default-lazy-init="true">
<dubbo:service interface="com.soukong.center.address.dubbo.service.AreaDubboService" ref="areaDubboService"/>
</beans>
调用方
<?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:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"
default-lazy-init="true">
<dubbo:application name="consumer" />
<dubbo:registry address="zookeeper://localhost:2181" check="false" />
<dubbo:reference interface="com.soukong.center.address.dubbo.service.AreaDubboService" id="areaDubboService" check="false" timeout="1200000" />
</beans>
注意有个是以 <dubbo:service interface=
。
一个是以:<dubbo:reference interface="
两个不一样。
数据库
application-jdbc.yml
## 关于数据库参数的相关配置
spring:
datasource:
name: mysql_test
type: com.alibaba.druid.pool.DruidDataSource
#druid相关配置
druid:
#监控统计拦截的filters
filters: stat
driver-class-name: com.mysql.jdbc.Driver
#基本属性
url: jdbc:mysql://localhost:3306/ware-center?characterEncoding=utf-8
username: root
password: 123456
#配置初始化大小/最小/最大
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 600000
#间隔多久进行一次检测,检测需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#一个连接在池中最小生存的时间
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
pom.xml
<!-- 阿里巴巴的Druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
表结构SQL
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50022
Source Host : localhost:3306
Source Database : ware-center
Target Server Type : MYSQL
Target Server Version : 50022
File Encoding : 65001
Date: 2019-03-11 10:05:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb_area
-- ----------------------------
DROP TABLE IF EXISTS `tb_area`;
CREATE TABLE `tb_area` (
`areaId` int(20) NOT NULL auto_increment COMMENT '地区Id',
`areaCode` varchar(50) NOT NULL COMMENT '地区编码',
`areaName` varchar(20) NOT NULL COMMENT '地区名',
`level` tinyint(4) default '-1' COMMENT '地区级别(1:省份province,2:市city,3:区县district,4:街道street)',
`cityCode` varchar(50) default NULL COMMENT '城市编码',
`center` varchar(50) default NULL COMMENT '城市中心点(即:经纬度坐标)',
`parentCode` varchar(50) default '-1' COMMENT '地区父节点',
`create_time` timestamp NOT NULL COMMENT '创建时间',
`update_time` timestamp NULL default NULL COMMENT '最后修改时间',
`del_flag` tinyint(1) default '0' COMMENT '删除状态 1-已删除 0-未删除',
`op_id` varchar(25) default NULL COMMENT '操作人',
`version` bigint(20) default '1' COMMENT '版本',
PRIMARY KEY (`areaId`),
KEY `areaCode` (`areaCode`),
KEY `parentId` (`parentCode`),
KEY `level` (`level`),
KEY `areaName` (`areaName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='地区码表';
常见异常
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'areaController': Unsatisfied dependency expressed through field 'areaDubboService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.soukong.center.address.dubbo.service.AreaDubboService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
'com.soukong.center.address.entity.AreaEntity' in your configuration.
org.thymeleaf.exceptions.TemplateInputException: Error resolving fragment: "~{'commons/header' :: copy}": template or fragment could not be resolved (
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buyerOrderController': Unsatisfied dependency expressed through field 'orderService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderServiceImpl': Unsatisfied dependency expressed through field 'productService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productServiceImpl': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productInfoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.imooc.dataobject.ProductInfo com.imooc.repository.ProductInfoRepository.findOne(java.lang.String)! No property findOne found for type ProductInfo!
Description:
Field sysMenuDao in com.soukong.center.manage.service.impl.SysMenuServiceImpl required a bean of type 'com.soukong.center.manage.dao.SysMenuDao' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.soukong.center.manage.dao.SysMenuDao' in your configuration.
java.lang.IllegalStateException:
Error
processing
condition on com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure.dataSource
java.lang.IllegalStateException:
Error processing condition on com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure.dataSource
java.lang.IllegalStateException: Error processing condition on com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure.dataSource
Caused by: java.lang.NoClassDefFoundError: com/alibaba/druid/filter/logging/Log4j2Filter
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Generic.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver
[ERROR] Failed to execute goal on project BZQ-B2B2C-MANEGE-CONTROLLER: Could not resolve dependencies for project com.bzqb2b2c.manage:BZQ-B2B2C-MANEGE-CONTROLLER:war:1.0-SNAPSHOT: The following artifacts could not be resolved: com.bzqb2b2c.manage:BZQ-B2B2C-MANEGE-API:jar:1.0-SNAPSHOT, com.bzqb2b2c.manage:BZQ-B2B2C-MANEGE-SERVICE:jar:1.0-SNAPSHOT: Could not find artifact com.bzqb2b2c.manage:BZQ-B2B2C-MANEGE-API:jar:1.0-SNAPSHOT -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
log4j:WARN No appenders could be found for logger (org.springframework.boot.devtools.settings.DevToolsSettings).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/other/maven/maven-dependcies/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/other/maven/maven-dependcies/org/slf4j/slf4j-log4j12/1.7.19/slf4j-log4j12-1.7.19.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
Consider defining a bean of type 'com.chengcheng.goods.service.sys.SysUserService' in your configuration.
java.lang.IllegalStateException: Configuration error: No realms have been configured! One or more realms must be present to execute an authentication attempt.
java.lang.IllegalStateException: Configuration error: No realms have been configured! One or more realms must be present to execute an authentication attempt.
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.b2b2c.ware.center.dao.ware.ConfigInfoDao.queryList
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
小结
一句话,坑无数,嘻嘻
源代码下载
版本3