初学 spring-boot , 在项目中整合了 MongoDB , MySQL 和 MyBatis , 记录下过程中遇到的一些问题和处理方法
一 创建一个 Spring-boot 项目 , 这里以 IntelliJ Idea 为例
工具栏 File >> new >> project
弹出窗口左侧栏选中 Spring initializr , JDK 版本可自选 , Service URL 用默认的就行, 如下图 :
点击 next , 对项目命名处理
Next , 选择整合内容 (MySQL + MongoDB + MyBatis)
Next >> finish 到这里 , 一个spring-boot 项目就创建完成了
关于服务启动方式 :
1 直接运行项目根目录下的 Main 方法
2 控制台 : 输入 mvn spring-boot:run
......
二 整合 MongoDB
关于目录结构 :
有个问题困扰了我很久 , 就是Main方法类貌似必须在根目录下 , 移动后 , 会导致bean注入失败 OR 访问 404
1 添加MongoDB配置 , 关于MongoDB的安装和相关一些简单操作,安利个地址 : MongoDB 菜鸟教程
#MongoDB 连接配置
spring.data.mongodb.uri=mongodb://moonlo:admin123@127.0.0.1:27017/test
2 测试代码
User.java
package com.example.SpringbootDemo.mongodb.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.io.Serializable;
/**
* 功能描述: MongoDB User 实体类
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-16 16:34
*/
@SuppressWarnings("serial")
@Document(collection = "runoob") //指定实体对应MongoDB的哪一个集合
public class User implements Serializable {
@Id
private String id;
@Field
private String testName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTestName() {
return testName;
}
public void setTestName(String name) {
this.testName = name;
}
}
IUserSevice.java
package com.example.SpringbootDemo.mongodb.service;
import com.example.SpringbootDemo.mongodb.domain.User;
import java.util.List;
/**
* 功能描述: MongoDB数据操作Service 接口
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-16 16:48
*/
public interface IUserService {
/**
* 保存用户
* @param user 返回保存的用户
*/
void saveUser(User user) ;
/**
* 查询所有用户
* @return 用户
*/
List<User> findAll() ;
/**
* 根据名字查询用户
* @param name 名字
* @return 用户
*/
List<User> findUserByName(String name) ;
}
UserServiceImpl.java
package com.example.SpringbootDemo.mongodb.service.impl;
import com.example.SpringbootDemo.mongodb.domain.User;
import com.example.SpringbootDemo.mongodb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 功能描述: MongoDB 数据操作Service 接口实现
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-16 16:50
*/
@Service("userService")//可以不用给定value,看个人习惯
public class UserServiceImpl implements IUserService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 保存用户
* @param user 返回保存的用户
*/
public void saveUser(User user) {
mongoTemplate.save(user);
}
@Override
public List<User> findAll() {
return mongoTemplate.findAll(User.class);
}
/**
* 根据名字查询用户
* @param name 名字
* @return 用户
*/
public List<User> findUserByName(String name) {
Query query = new Query(Criteria.where("testName").is(name));
List<User> users = mongoTemplate.find(query, User.class);
return users;
}
}
SpringBootTestController.java
package com.example.SpringbootDemo.mongodb.controller;
import com.example.SpringbootDemo.mongodb.domain.User;
import com.example.SpringbootDemo.mongodb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 功能描述: 测试控制类-提供浏览器访问
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-17 15:51
*/
@RestController
public class SpringBootTestController {
@Autowired
private IUserService userService;
@RequestMapping("/findAll")
public List<User> findAll(){
List<User> users = userService.findAll();
return users;
}
@RequestMapping("/find/{testName}")
public String find(@PathVariable("testName") String testName){
List<User> users = userService.findUserByName(testName);
String str = "";
for (User user : users){
str += "\n" + user.getId() + user.getTestName();
}
return "find success..." + "\n" + str;
}
@RequestMapping("/save/{testName}")
public String insert(@PathVariable("testName") String testName){
User user = new User();
user.setTestName(testName);
userService.saveUser(user);
return "save success...";
}
}
服务启动成功后 , 浏览器端访问 : http://localhost:8080/findAll
需要注意的是 , springboot 服务默认的端口是 8080 , 要变更的话 , 需要在配置里面变更
#MongoDB 连接配置
spring.data.mongodb.uri=mongodb://moonlo:admin123@localhost:27017/test
#日志文件输出地址&文件名
logging.file=logs/config/spring-boot-demo.log
#服务端口号
server.port=8888
#session 超时时间
server.servlet.session.timeout=10s
#编码设置
server.tomcat.uri-encoding=UTF-8
三 整合 MySQL + MyBatis
1 添加配置信息 , 需要注意MySQL版本不同 , 引入的Driver会有差别
#MongoDB 连接配置
spring.data.mongodb.uri=mongodb://moonlo:admin123@localhost:27017/test
#日志文件地址&文件名
logging.file=logs/config/spring-boot-demo.log
#服务端口号
server.port=8888
#session 超时时间
server.servlet.session.timeout=10s
#编码设置
server.tomcat.uri-encoding=UTF-8
#MySql 连接配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/moon?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong
spring.datasource.username=moon
spring.datasource.password=admin123
#mysql8 以后的Driver 需要用 com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
#MyBatis 扫描文件
mybatis.mapper-locations=classpath:mappers/*.xml
2 测试代码
MysqlDemo.java
package com.example.SpringbootDemo.mongodb.domain;
import java.io.Serializable;
/**
* 功能描述: MySQL 数据测试实体类
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-18 10:04
*/
@SuppressWarnings("serial")
public class MysqlDemo implements Serializable {
private Long sysStockDetailId;
private String remark;
public Long getSysStockDetailId() {
return sysStockDetailId;
}
public void setSysStockDetailId(Long sysStockDetailId) {
this.sysStockDetailId = sysStockDetailId;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
MysqlDao.java
package com.example.SpringbootDemo.mongodb.dao;
import com.example.SpringbootDemo.mongodb.domain.MysqlDemo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 功能描述: Mysql 数据访问Dao
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-18 10:08
*/
@Mapper
@Component(value = "mysqlDao") //解决Service层 @AutoWire 提示错误
public interface MysqlDao {
/**
* 查询所有
* @return all
*/
List<MysqlDemo> queryAll();
}
MySQLService.java
package com.example.SpringbootDemo.mongodb.service.impl;
import com.example.SpringbootDemo.mongodb.dao.MysqlDao;
import com.example.SpringbootDemo.mongodb.domain.MysqlDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 功能描述: Mysql 数据访问 Service
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-18 10:11
*/
@Service
public class MySQLService {
@Autowired
private MysqlDao mysqlDao;
public List<MysqlDemo> queryAll() throws RuntimeException{
return mysqlDao.queryAll();
}
}
SpringBootDemoMapper.xml
<?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.example.SpringbootDemo.mongodb.dao.MysqlDao">
<select id="queryAll" resultType="com.example.SpringbootDemo.mongodb.domain.MysqlDemo">
select
d.sys_stock_detail_id as sysStockDetailId,
d.remark
from sys_stock_detail d
</select>
</mapper>
SpringBootTestController.java
package com.example.SpringbootDemo.mongodb.controller;
import com.example.SpringbootDemo.mongodb.domain.MysqlDemo;
import com.example.SpringbootDemo.mongodb.domain.User;
import com.example.SpringbootDemo.mongodb.service.IUserService;
import com.example.SpringbootDemo.mongodb.service.impl.MySQLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 功能描述: 测试控制类-提供浏览器访问
* Copyright: Copyright (c) 2018
* Company: Lyl
* @author Uncle Drew
* @version 1.0 2019-01-17 15:51
*/
@RestController
public class SpringBootTestController {
@Autowired
private IUserService userService;
@Autowired
private MySQLService mySQLService;
/**
* MongoDB 拉取集合所有数据
* @return 返回所有集合信息
*/
@RequestMapping("/findAll")
public List<User> findAll(){
List<User> users = userService.findAll();
return users;
}
/**
* MongoDB 根据对应key值拉取集合数据
* @return 返回对应集合信息
*/
@RequestMapping("/find/{testName}")
public String find(@PathVariable("testName") String testName){
List<User> users = userService.findUserByName(testName);
String str = "";
for (User user : users){
str += "\n" + user.getId() + user.getTestName();
}
return "find success..." + "\n" + str;
}
/**
* MongoDB 新增集合数据
*/
@RequestMapping("/save/{testName}")
public String insert(@PathVariable("testName") String testName){
User user = new User();
user.setTestName(testName);
userService.saveUser(user);
return "save success...";
}
/**
* MySQL 拉取测试表所有数据
* @return 测试表所有数据
*/
@RequestMapping("/queryAll")
public List<MysqlDemo> queryAll(){
List<MysqlDemo> results = mySQLService.queryAll();
return results;
}
}
服务启动成功后 , 浏览器访问 : http://localhost:8888/queryAll
相关代码已上传 GitHub : https://github.com/MoonLo/repository/tree/master/SpringbootDemo