title: 好客租房mybatisplus
date: 2019-08-22 13:31:34
categories: 项目实战
tags:
基于dubbo react mybatisplus elk实战整合开发
docker run -di --name=mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 docker.io/mysql
mysql -u root -p
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
docker logs -fn 500 mysql
执行建表 haoke.sql
mybatis-plus/pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
dependencies>
application.properties
spring.application.name = itcast-mybatis-plus
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.3.237:3306/haoke?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
com/onejane/mybatisplus/pojo/User.java
@Data
public class User {
@TableId(value = "ID", type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
com/onejane/mybatisplus/mapper/UserMapper.java
public interface UserMapper extends BaseMapper<User> {
}
com/onejane/mybatisplus/MyApplication.java
@MapperScan("com.onejane.mybatisplus.mapper") //设置mapper接口的扫描包
@SpringBootApplication
public class MyApplication {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
com/onejane/mybatisplus/mapper/UserMaperTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMaperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect(){
List users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testSelectById(){
User user = this.userMapper.selectById(3L);
System.out.println(user);
}
@Test
public void testSelectByLike(){
QueryWrapper wrapper = new QueryWrapper();
wrapper.like("name", "o");
List list = this.userMapper.selectList(wrapper);
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testSelectByLe(){
QueryWrapper wrapper = new QueryWrapper();
wrapper.le("age", 20);
List list = this.userMapper.selectList(wrapper);
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testSave(){
User user = new User();
user.setAge(25);
user.setEmail("[email protected]");
user.setName("zhangsan");
int count = this.userMapper.insert(user);
System.out.println("新增数据成功! count => " + count);
}
@Test
public void testDelete(){
this.userMapper.deleteById(7L);
System.out.println("删除成功!");
}
@Test
public void testUpdate(){
User user = new User();
user.setId(6L);
user.setName("lisi");
this.userMapper.updateById(user);
System.out.println("修改成功!");
}
@Test
public void testSelectPage() {
Page page = new Page<>(2, 2);
IPage userIPage = this.userMapper.selectPage(page, null);
System.out.println("总条数 ------> " + userIPage.getTotal());
System.out.println("当前页数 ------> " + userIPage.getCurrent());
System.out.println("当前每页显示数 ------> " + userIPage.getSize());
List records = userIPage.getRecords();
for (User user : records) {
System.out.println(user);
}
}
}
兼容配置application.properties
## 指定全局配置文件
mybatis-plus.config-location = classpath:mybatis-config.xml
# 指定mapper.xml文件
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
<version>1.18.4version>
dependency>
安装idea Lombok插件
@Slf4j
@Data
@AllArgsConstructor
@Builder
public class Item {
private Long id;
private String title;
private Long price;
public Item() {
log.info("写日志。。。。。");
}
public static void main(String[] args) {
Item item1 = new Item(1L,"哈哈哈",10L);
Item item2 = Item.builder().price(100L)title("hello").id(1L).build();
System.out.println(item1.getId());
}
}
haoke-manage
├─haoke-manage-api-server
├─haoke-manage-dubbo-server
│ ├─haoke-manage-dubbo-server-ad
│ ├─haoke-manage-dubbo-server-common
│ ├─haoke-manage-dubbo-server-generator MybatisPlus的AutoGenerator插件生成代码文件
│ ├─haoke-manage-dubbo-server-house-resources
│ │ ├─haoke-manage-dubbo-server-house-resources-dubbo-interface 对外提供的sdk包 只提供pojo实体以及接口,不提供实现类
│ │ ├─haoke-manage-dubbo-server-house-resources-dubbo-service 具体实现
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.0.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibaba.bootgroupId>
<artifactId>dubbo-spring-boot-starterartifactId>
<version>0.2.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>dubboartifactId>
<version>2.6.4version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.7version>
dependency>
<dependency>
<groupId>org.apache.zookeepergroupId>
<artifactId>zookeeperartifactId>
<version>3.4.13version>
dependency>
<dependency>
<groupId>com.github.sgroschupfgroupId>
<artifactId>zkclientartifactId>
<version>0.1version>
dependency>
dependencies>
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.onejanegroupId>
<artifactId>haoke-manage-dubbo-server-house-resources-dubbo-interfaceartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
dependencies>
application.properties
# Spring boot application
spring.application.name = haoke-manage-api-server
server.port = 18080
#logging.level.root=DEBUG
# dubbo的应用名称
dubbo.application.name = dubbo-consumer-haoke-manage
# zk注册中心
dubbo.registry.address = zookeeper://192.168.3.237:2181
dubbo.registry.client = zkclient
Pagination
@Data
@AllArgsConstructor
public class Pagination {
private Integer current;
private Integer pageSize;
private Integer total;
}
TableResult
@Data
@AllArgsConstructor
public class TableResult<T> {
private List<T> list;
private Pagination pagination;
}
HouseResourcesService
@Service
public class HouseResourcesService {
@Reference(version = "1.0.0")
private ApiHouseResourcesService apiHouseResourcesService;
public boolean save(HouseResources houseResources) {
int result =
this.apiHouseResourcesService.saveHouseResources(houseResources);
return result == 1;
}
public TableResult queryList(HouseResources houseResources, Integer currentPage, Integer pageSize) {
PageInfo pageInfo = this.apiHouseResourcesService.
queryHouseResourcesList(currentPage, pageSize, houseResources);
return new TableResult<>(pageInfo.getRecords(), new Pagination(currentPage, pageSize, pageInfo.getTotal()));
}
/**
* 根据id查询房源数据
*
* @param id
* @return
*/
public HouseResources queryHouseResourcesById(Long id){
// 调用dubbo中的服务进行查询数据
return this.apiHouseResourcesService.queryHouseResourcesById(id);
}
public boolean update(HouseResources houseResources) {
return this.apiHouseResourcesService.updateHouseResources(houseResources);
}
}
HouseResourcesController
@Controller
@RequestMapping("house/resources")
public class HouseResourcesController {
@Autowired
private HouseResourcesService houseResourcesService;
/**
* 新增房源
*
* @param houseResources json数据
* @return
*/
@PostMapping
@ResponseBody
public ResponseEntity<Void> save(@RequestBody HouseResources houseResources) {
try {
boolean bool = this.houseResourcesService.save(houseResources);
if (bool) {
return ResponseEntity.status(HttpStatus.CREATED).build();
}
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
/**
* 查询房源列表
*
* @param houseResources
* @param currentPage
* @param pageSize
* @return
*/
@GetMapping
@ResponseBody
public ResponseEntity<TableResult> list(HouseResources houseResources,
@RequestParam(name = "currentPage",
defaultValue = "1") Integer currentPage,
@RequestParam(name = "pageSize",
defaultValue = "10") Integer pageSize) {
return ResponseEntity.ok(this.houseResourcesService.queryList(houseResources, currentPage,
pageSize));
}
/**
* 修改房源
*
* @param houseResources json数据
* @return
*/
@PutMapping
@ResponseBody
public ResponseEntity<Void> update(@RequestBody HouseResources houseResources) {
try {
boolean bool = this.houseResourcesService.update(houseResources);
if (bool) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
DubboApiApplication
@SpringBootApplication
public class DubboApiApplication {
public static void main(String[] args) {
SpringApplication.run(DubboApiApplication.class, args);
}
}
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
dependencies>
pom.xml
<dependencies>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.28version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
<optional>trueoptional>
dependency>
dependencies>
CodeGenerator 配置数据源及账户密码,运行即可生成对应文件,并将pojo类拷贝到工程中备用
public class CodeGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("onejane");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.3.237:3306/haoke?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.onejane.haoke.dubbo.server");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" +
pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" +
StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.onejane.haoke.dubbo.server.pojo.BasePojo");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
strategy.setInclude(scanner("表名"));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
测试
[外链图片转存失败(img-M2VX7S0W-1566470498492)(https://www.github.com/OneJane/blog/raw/master/小书匠/1566452133968.png)]
pom.xml
<dependencies>
<dependency>
<groupId>com.onejanegroupId>
<artifactId>haoke-manage-dubbo-server-commonartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
<optional>trueoptional>
dependency>
dependencies>
ApiHouseResourcesService
// dubbo service
public interface ApiHouseResourcesService {
/**
* 新增房源
*
* @param houseResources
* @return -1:输入的参数不符合要求,0:数据插入数据库失败,1:成功
*/
int saveHouseResources(HouseResources houseResources);
/**
* 分页查询房源列表
*
* @param page 当前页
* @param pageSize 页面大小
* @param queryCondition 查询条件
* @return
*/
PageInfo<HouseResources> queryHouseResourcesList(int page, int pageSize,
HouseResources queryCondition);
/**
* 根据id查询房源数据
*
* @param id
* @return
*/
HouseResources queryHouseResourcesById(Long id);
boolean updateHouseResources(HouseResources houseResources);
}
HouseResources
@Data
@Accessors(chain = true)
@TableName("tb_house_resources")
public class HouseResources extends BasePojo {
private static final long serialVersionUID = 779152022777511825L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 房源标题
*/
private String title;
/**
* 楼盘id
*/
private Long estateId;
/**
* 楼号(栋)
*/
private String buildingNum;
/**
* 单元号
*/
private String buildingUnit;
/**
* 门牌号
*/
private String buildingFloorNum;
/**
* 租金
*/
private Integer rent;
/**
* 租赁方式,1-整租,2-合租
*/
private Integer rentMethod;
/**
* 支付方式,1-付一押一,2-付三押一,3-付六押一,4-年付押一,5-其它
*/
private Integer paymentMethod;
/**
* 户型,如:2室1厅1卫
*/
private String houseType;
/**
* 建筑面积
*/
private String coveredArea;
/**
* 使用面积
*/
private String useArea;
/**
* 楼层,如:8/26
*/
private String floor;
/**
* 朝向:东、南、西、北
*/
private String orientation;
/**
* 装修,1-精装,2-简装,3-毛坯
*/
private Integer decoration;
/**
* 配套设施, 如:1,2,3
*/
private String facilities;
/**
* 图片,最多5张
*/
private String pic;
/**
* 描述
*/
private String houseDesc;
/**
* 联系人
*/
private String contact;
/**
* 手机号
*/
private String mobile;
/**
* 看房时间,1-上午,2-中午,3-下午,4-晚上,5-全天
*/
private Integer time;
/**
* 物业费
*/
private String propertyCost;
}
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>com.onejanegroupId>
<artifactId>haoke-manage-dubbo-server-house-resources-dubbo-interfaceartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
dependencies>
application.properties
# Spring boot application
spring.application.name = haoke-manage-dubbo-server-house-resources
# 数据库
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.3.237:3306/haoke?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# 服务的扫描包
dubbo.scan.basePackages = com.onejane.haoke.dubbo.server.api
# 应用名称
dubbo.application.name = dubbo-provider-house-resources
# 协议以及端口
dubbo.protocol.name = dubbo
dubbo.protocol.port = 20880
# zk注册中心
dubbo.registry.address = zookeeper://192.168.3.237:2181
dubbo.registry.client = zkclient
MybatisConfig
@MapperScan("com.onejane.haoke.dubbo.server.mapper")
@Configuration
public class MybatisConfig {
}
HouseResourcesMapper
public interface HouseResourcesMapper extends BaseMapper<HouseResources> {
}
HouseResourcesService
// spring service
public interface HouseResourcesService {
/**
* @param houseResources
*
* @return -1:输入的参数不符合要求,0:数据插入数据库失败,1:成功
*/
int saveHouseResources(HouseResources houseResources);
PageInfo queryHouseResourcesList(int page, int pageSize, HouseResources queryCondition);
/**
* 根据房源id查询房源数据
*
* @param id
* @return
*/
HouseResources queryHouseResourcesById(Long id);
/**
* 更新房源数据
*
* @param houseResources
* @return
*/
boolean updateHouseResources(HouseResources houseResources);
}
HouseResourcesServiceImpl
@Transactional
@Service
public class HouseResourcesServiceImpl extends BaseServiceImpl implements HouseResourcesService {
/**
* @param houseResources
* @return -1:输入的参数不符合要求,0:数据插入数据库失败,1:成功
*/
@Override
public int saveHouseResources(HouseResources houseResources) {
// 添加校验或者是其他的一些逻辑
if (StringUtils.isBlank(houseResources.getTitle())) {
// 不符合要求
return -1;
}
return super.save(houseResources);
}
@Override
public PageInfo queryHouseResourcesList(int page, int pageSize, HouseResources queryCondition) {
QueryWrapper queryWrapper = new QueryWrapper();
// 根据数据的更新时间做倒序排序
queryWrapper.orderByDesc("updated");
IPage iPage = super.queryPageList(queryWrapper, page, pageSize);
return new PageInfo(Long.valueOf(iPage.getTotal()).intValue(), page, pageSize, iPage.getRecords());
}
public HouseResources queryHouseResourcesById(Long id) {
return super.queryById(id);
}
@Override
public boolean updateHouseResources(HouseResources houseResources) {
return super.update(houseResources) == 1;
}
}
DubboProvider
@SpringBootApplication
public class DubboProvider {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
public static void main(String[] args) {
new SpringApplicationBuilder(DubboProvider.class)
.web(WebApplicationType.NONE) // 非 Web 应用
.run(args);
}
}
ApiHouseResourcesServiceImpl
@Service(version = "1.0.0")
// 分离dubbo服务和spring服务,易于扩展
public class ApiHouseResourcesServiceImpl implements ApiHouseResourcesService {
@Autowired
private HouseResourcesService houseResourcesService;
@Override
public int saveHouseResources(HouseResources houseResources) {
return this.houseResourcesService.saveHouseResources(houseResources);
}
@Override
public PageInfo queryHouseResourcesList(int page, int pageSize, HouseResources queryCondition) {
return this.houseResourcesService.queryHouseResourcesList(page, pageSize, queryCondition);
}
public HouseResources queryHouseResourcesById(Long id) {
return this.houseResourcesService.queryHouseResourcesById(id);
}
@Override
public boolean updateHouseResources(HouseResources houseResources) {
return this.houseResourcesService.updateHouseResources(houseResources);
}
}
启动DubboAdmin中显示
[外链图片转存失败(img-ChSU8X9w-1566470498494)(https://www.github.com/OneJane/blog/raw/master/小书匠/1566460308284.png)]
[外链图片转存失败(img-lQ4Xec2N-1566470498495)(https://www.github.com/OneJane/blog/raw/master/小书匠/1566469160972.png)]
[外链图片转存失败(img-LGPFssRv-1566470498496)(https://www.github.com/OneJane/blog/raw/master/小书匠/1566469175813.png)]
src/pages/haoke/House/AddResource.js
添加标题及修改表单提交地址
{getFieldDecorator('title',{rules:[{ required: true, message:"此项为必填项" }]})()}
dispatch({
type: 'house/submitHouseForm',
payload: values,
});
src/pages/haoke/House/models/form.js
增加model
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { addHouseResource } from '@/services/haoke';
export default {
namespace: 'house',
state: {
},
effects: {
*submitHouseForm({ payload }, { call }) {
yield call(addHouseResource, payload);
message.success('提交成功');
}
},
reducers: {
saveStepFormData(state, { payload }) {
return {
...state
};
},
},
};
src/services/haoke.js
增加服务,请求服务并且处理业务逻辑
import request from '@/utils/request';
export async function addHouseResource(params) {
return request('/haoke/house/resources', {
method: 'POST',
body: params
});
}
由于我们前端系统8000和后台服务系统18080的端口不同,会导致跨域问题,我们通过umi提供的反向代理功能解决这个问题。
haoke-manage-web/config/config.js
proxy: {
'/haoke/': {
target: 'http://127.0.0.1:18080/',
changeOrigin: true,
pathRewrite: { '^/haoke/': '' }
}
},
代理效果是这样的:以haoke开头的请求都会被代理
请求:http://localhost:8000/haoke/house/resources
实际:http://127.0.0.1:18080/house/resources
启动前端:itcast-haoke-manage-web>tyarn start
启动提供者:itcast-haoke-manage-dubbo-server-house-resources-dubbo-service/DubboProvider
启动消费者:tcast-haoke-manage/itcast-haoke-manage-api-server/DubboApiApplication
[外链图片转存失败(img-Yu9Nvffl-1566470498497)(https://www.github.com/OneJane/blog/raw/master/小书匠/1566452323332.png)]