前言
经过打工人的不懈努力,终于敲出了多层封装的安卓前后端分离项目的雏形。
前期准备
开发环境:
(1)jdk1.8
(2)Android stdio 4.1 (包含自带的Gradle)
(3)IntelliJ IDEA 2020.2.3 x64 (包含配置好的的Maven)
项目框架及依赖
安卓用了OKHttp
后端用了springboot+mybatis-plus
安卓前端的gradle依赖
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation 'com.google.code.gson:gson:2.7'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
springboot项目的maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
后端搭建
1.通过mybatis-plus模板生成
根据数据库中的表user创建
生成mvc代码:Generate.java(要放在包的最外层,与初始的springboot启动类平级的位置,例如:放在com.example下)
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
public class Generate {
public static void main(String[] args) {
//创建generator对象
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("123456");
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/dbName");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");
globalConfig.setAuthor("admin");
globalConfig.setOpen(false);
globalConfig.setServiceName("%sService");
autoGenerator.setGlobalConfig(globalConfig);
//包信息
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example");//包名
packageConfig.setEntity("entity");
packageConfig.setMapper("mapper");
packageConfig.setService("service");
packageConfig.setServiceImpl("service.impl");
packageConfig.setController("controller");
autoGenerator.setPackageInfo(packageConfig);
//策略配置
StrategyConfig strategyConfig = new StrategyConfig();
String tablesName="user";
strategyConfig.setInclude(tablesName);
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);
autoGenerator.setStrategy(strategyConfig);
//运行
autoGenerator.execute();
}
}
生成结果:(没有util)
创建一个结果类Result,用来装结果集(第三个参数装json字符串)
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class Result {
private int code;
private String msg;
private String result;
public void setSuccess(String msg, String result){
this.code=200;
this.msg="success-"+msg;
this.result=result;
}
public void setInfo(String msg, String result){
this.code=400;
this.msg="warning-"+msg;
this.result=result;
}
}
配置文件application改成yml后缀
application.yml内容为:
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_name
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/example/mapper/xml/*.xml
server:
port: 8081
控制层:
import com.campus.book.entity.Result;
import com.campus.book.entity.User;
import com.campus.book.service.UserService;
import com.campus.book.util.JsonBean;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
@RestController
@RequestMapping("//user")
public class UserController {
@Autowired
private UserService userService;
Gson gson= new GsonBuilder().serializeNulls().create();
Result result=new Result();
@PostMapping("/insert")
public Result insert(String json){
User user=null;
try{
user=gson.fromJson(json,User.class);
}catch (Exception e){
e.printStackTrace();
}
if(userService.getById(user.getId())!=null){
//id重复!
result.setInfo("该账号已注册!",null);
}else{
userService.save(user);
result.setSuccess("注册成功!",gson.toJson(user));
}
return result;
}
@DeleteMapping("/delete/{id}")
public Result delete(@PathVariable("id") Serializable id) {
result.setSuccess("删除成功!", null);
boolean is=this.userService.removeById(id);
if(is){
}else{
result.setInfo("删除失败!",null);
}
return result;
}
@PutMapping("/update")
public Result update(String json) {
result.setInfo("更改失败!",json);
User user=null;
try{
user=gson.fromJson(json,User.class);
if(this.userService.updateById(user)){
result.setSuccess("更改成功!",gson.toJson(userService.getById(user.getId())));
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
@GetMapping("/list")
public Result list() {
result.setSuccess("查询成功!", gson.toJson(this.userService.list()));
return result;
}
@GetMapping("/line/{id}")
public Result getUser(@PathVariable("id") Serializable id){
User user=userService.getById(id);
if(user!=null){
//存在
result.setSuccess("查询成功!",gson.toJson(user));
}else{
//不存在
result.setSuccess("没有找到相关数据!",null);
}
return result;
}