SpringBoot 项目练习
1. 创建SpringBoot项目
2. 编辑 application.properties 配置文件
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/tliasdb
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=root
#配置mybatis的日志, 指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关 a_column ------> aCloumn
mybatis.configuration.map-underscore-to-camel-case=true
3. 创建实体类
- 编辑统一结果实体
package com.practice.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Integer code;//响应码,1 代表成功; 0 代表失败
private String msg; //响应信息 描述字符串
private Object data; //返回的数据
//增删改 成功响应
public static Result success(){
return new Result(1,"success",null);
}
//查询 成功响应
public static Result success(Object data){
return new Result(1,"success",data);
}
//失败响应
public static Result error(String msg){
return new Result(0,msg,null);
}
}
4. 创建web三层架构
5. 为各层添加接口
- 控制层(Controller)
- 添加 @RestController 注解,该注解包含了@Controller和@ResponseBody
- 服务层(Service)
- 添加@Service注解
- 持久层(Dao)
- 添加@Mapper注解
6. 代码实现
- 控制层
package com.practice.controller;
import com.practice.pojo.Account;
import com.practice.pojo.Result;
import com.practice.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class AccountController {
@Autowired
AccountService as;
@RequestMapping("/hello")
Result findAll() {
List<Account> list = as.findAll();
list.forEach(System.out::println);
return Result.success(list);
}
}
- 服务层
接口
package com.practice.service;
import com.practice.pojo.Account;
import org.springframework.stereotype.Service;
import java.util.List;
public interface AccountService {
List<Account> findAll();
}
**实现类**
package com.practice.service.impl;
import com.practice.mapper.AccountMapper;
import com.practice.pojo.Account;
import com.practice.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
AccountMapper am;
@Override
public List<Account> findAll() {
return am.findAll();
}
}
- 持久层
package com.practice.mapper;
import com.practice.pojo.Account;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AccountMapper {
@Select("select * from account")
List<Account> findAll();
}
- 数据库内容
- 浏览器访问结果