SpringBoot简化了太多步骤,真心强大,当没有接触它的时候,Mybatis还要写dao层接口,还要dao层映射的sql语句,虽然也有一键生成相关配置。但是繁琐的配置,需要配置xml扫描相关路径等,springBoot通通不需要使用JPA关联数据库。
JPA中有许多封装好的对数据库进行操作的方法,不需要再写sql语句,而是直接调用其中的方法,就可以完成对数据的操作了。而这时,持久层只需继承JpaRepository类就行啦。要是创建接口方法可以直接声明一个方法,然后用findby… 后面接的是关键字来查询,真的神器呀
1、创建springboot
一直下一步,完成创建
添加pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--get、set简写-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!--参数动态注入,用到模板技术-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--mybatis的包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
2、application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/sell?characterEncoding=utf-8&&useSSL=false&&serverTimezone=UTC
jpa:
show-sql: true
server:
servlet:
context-path: /sell
3、 创建数据库sell.sql
create table `product_category`(
`category_id` int not null auto_increment,
`category_name` varchar(64) not null comment '类目名字',
`category_type` int not null comment '类目编号',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp
comment '修改时间',
primary key (`category_id`),
unique key `uqe_category_type` (`category_type`)
)comment '类目表';
CREATE TABLE `product_info` (
`product_id` varchar(32) NOT NULL,
`product_name` varchar(64) NOT NULL COMMENT '商品名称',
`product_price` decimal(8,2) NOT NULL COMMENT '单价',
`product_description` varchar(64) DEFAULT NULL COMMENT '描述',
`category_type` int(11) NOT NULL COMMENT '类目编号',
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品表';
4、dao层接口
4.1 类目ProductCategoryDao
继承JpaRepository
JPA
(1)与hibernate的关系:jpa是标准,实际上,jpa只是定义了接口,实现都是hibernate在做。
(2)jpa存在的目的:让spring实现持久化操作,spring本来对第三方框架的整合上的特别的好。
不用写相对繁琐的配置,简单明了
Spring提供了一套可以通过命名规则进行查询构建的机制。这套机制会把方法名首先过滤一些关键字,比如 find…By, read…By, query…By, count…By 和 get…By 。系统会根据关键字将命名解析成2个子语句,第一个 By 是区分这两个子语句的关键词。这个 By 之前的子语句是查询子语句(指明返回要查询的对象),后面的部分是条件子语句。如果直接就是 findBy… 返回的就是定义Respository时指定的领域对象集合
这里一个新方法,是为了通过type来查询
也不需要写入sql映射,用来做对比。假如要查所有的列表信息,直接在service中实现就行,dao层都不用写那么复杂
public interface ProductCategoryDao extends JpaRepository<ProductCategory,Integer> {
//查商品希望查所有类目
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
4.2 商品详情ProductInfoDao
public interface ProductInfoDao extends JpaRepository<ProductInfo,String> {
}
5、实体类ProductCategory
商品类目实体类ProductCategory
//数据库映射成对象
@Entity
//动态更新时间
@DynamicUpdate
//无需getter和setter,界面干净
@Data
public class ProductCategory implements Serializable {
/** 类目id. */
//主键加自增类型
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;
/** 类目名字. */
private String categoryName;
/** 类目编号. */
private Integer categoryType;
private Date createTime;
private Date updateTime;
}
商品详情实体类ProductInfo
@Entity
@Data
public class ProductInfo implements Serializable {
@Id
private String productId;
/** 名字. */
private String productName;
/** 单价. */
private BigDecimal productPrice;
/** 描述. */
private String productDescription;
/** 类目编号. */
private Integer categoryType;
}
这里使用插件lombok
下载,并映入xml(前面有)
6、service层
6.1 商品类目接口 CategoryService
public interface CategoryService {
//查询记录提供
ProductCategory find0ne(Integer categoryId);
//查询所有
List<ProductCategory> findAll();
//通过tpye来查
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
6.2 商品类目实现接口 CategoryServiceImpl
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
private ProductCategoryDao productCategoryDao;
@Override
public ProductCategory find0ne(Integer categoryId) {
return productCategoryDao.findById(categoryId).orElse(null);
}
@Override
public List<ProductCategory> findAll() {
return productCategoryDao.findAll();
}
@Override
public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) {
return productCategoryDao.findByCategoryTypeIn(categoryTypeList);
}
}
6.3 商品详情的service层接口 ProductService
public interface ProductService {
//查询在架的商品列表
List<ProductInfo> findAll();
}
6.4 商品详情的service 实现接口 ProductServiceImpl
实现查询所有的商品
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductInfoDao productInfoDao;
//查询所有
@Override
public List<ProductInfo> findAll() {
return productInfoDao.findAll();
}
}
7、 控制层CategoryController
@RestController
@RequestMapping("/user/product")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
public ResultVO list(){
//查询所有
List<ProductCategory> productCategoryList = categoryService.findAll();
//数据拼装
List<ProductCategory> productCategoryVOList =new ArrayList<>();
for (ProductCategory productCategory:productCategoryList) {
ProductCategory productCategory1 =new ProductCategory();
productCategory1.setCategoryId(productCategory.getCategoryId());
productCategory1.setCategoryType(productCategory.getCategoryType());
productCategory1.setCategoryName(productCategory.getCategoryName());
productCategory1.setCreateTime(productCategory.getCreateTime());
productCategory1.setUpdateTime(productCategory.getUpdateTime());
productCategoryVOList.add(productCategory1);
}
ResultVO resultVO = new ResultVO();
resultVO.setCode(0);
resultVO.setMsg("成功");
resultVO.setData(productCategoryVOList);
return resultVO;
}
}
运行成功
数据库对照
8、拓展
将不同种类的种类区分开,这里奶茶对应有不同的类别的奶茶,如珍珠,布丁啥的,水果就是另一种分类。
并且不用把实体类中的所有属性都添加进去,方便以后调用
这里就需要定义两个工具类
9、首先创建两个工具类
商品类目ProductVO
商品详情ProductInfoVO
加入@JsonPropert注解,是为了前端要几个字段就用几个字段,不需要返回内容,也是出于对内容和隐私的考虑
@Data
public class ProductVO implements Serializable {
@JsonProperty("name")
private String categoryName;
@JsonProperty("type")
private Integer categoryType;
//这里声明了一个List是为了food里面所包含的所有商品信息
@JsonProperty("foods")
private List<ProductInfoVO> productInfoVOList;
}
@Data
public class ProductInfoVO implements Serializable {
@JsonProperty("id")
private String productId;
@JsonProperty("name")
private String productName;
@JsonProperty("price")
private BigDecimal productPrice;
@JsonProperty("description")
private String productDescription;
}
10 、下面重写controller层
类目下面具体的商品信息,进行具体的数据库传入
@RestController
@RequestMapping("/user/product")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@Autowired
private ProductService productService;
@GetMapping("/list")
public ResultVO list(){
//查询所有
List<ProductInfo> productInfoList =productService.findAll();
//2、查询类目(一次性查询)
List<Integer> categoryTypeList =new ArrayList<>();
//categoryTypeList从productInfoList这里面取
//for循环
for (ProductInfo productInfo : productInfoList){
categoryTypeList.add(productInfo.getCategoryType());
}
List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
//数据拼装
List<ProductVO> productVOList =new ArrayList<>();
for (ProductCategory productCategory:productCategoryList) {
ProductVO productVO =new ProductVO();
productVO.setCategoryType(productCategory.getCategoryType());
productVO.setCategoryName(productCategory.getCategoryName());
List<ProductInfoVO> productInfoVOList =new ArrayList<>();
//(2)下面在遍历商品详情
for (ProductInfo productInfo:productInfoList){
if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
ProductInfoVO productInfoVO =new ProductInfoVO();
//要写4个值,要写四遍,spring提供BeanUtils
//可以把productInfo拷贝到productInfoVO中去
BeanUtils.copyProperties(productInfo,productInfoVO);
productInfoVOList.add(productInfoVO);
}
}
productVO.setProductInfoVOList(productInfoVOList);
productVOList.add(productVO);
}
ResultVO resultVO = new ResultVO();
resultVO.setCode(0);
resultVO.setMsg("成功");
resultVO.setData(productVOList);
return resultVO;
}
}
再次运行,达到效果图
总结,SpringBoot使用Jpa来完成数据库的数据传入真的很方便,不像MyBatis那样还需要,写入sql语句映射,还要配置过滤器等,相当繁琐。springBoot真的是懒人的福利,减少不必要的代码量。我还发现,大多公司招聘网站好像没有几个写Mybatis的,看来,现在都是追求快速的,有效的,开心的打代码。哈哈!