Spring Boot微信点餐——实战开发DAO层

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 0. 修改grade镜像,使用阿里云地址,以便于快速加载依赖参照大佬博客 =====> 阿里云maven镜像 # 项目目录下的build.gradlerepositories { maven {url 'http://maven.
0. 修改grade镜像,使用阿里云地址,以便于快速加载依赖
参照大佬博客 =====> 阿里云maven镜像
 
# 项目目录下的build.gradle

repositories {
        maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        mavenLocal()
        mavenCentral()
 }

 

# 或者找到GRADLE_HOME/init.d/   或者是 GRADLE_HOME/init.d/  
# .gradle目录下新建init.gradle文件

allprojects{
    repositories {
        def REPOSITORY_URL = 'http://maven.aliyun.com/nexus/content/groups/public/'
        all { ArtifactRepository repo ->
            if(repo instanceof MavenArtifactRepository){
                def url = repo.url.toString()
                if (url.startsWith('https://repo1.maven.org/maven2') || url.startsWith('https://jcenter.bintray.com/')) {
                    project.logger.lifecycle "Repository ${repo.url} replaced by $REPOSITORY_URL."
                    remove repo
                }
            }
        }
        maven {
            url REPOSITORY_URL
        }
    }
}
 
1. 添加mysql依赖,添加JPA依赖
参照大神博客 =====>   mysql依赖
 
# 项目build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.9.RELEASE'
    }
    repositories {
        mavenLocal()
        mavenCentral()
        maven { url 'http://repo.spring.io/plugins-release' }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.dante.imooc'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    runtime('mysql:mysql-connector-java')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

 

 
然后在resources目录下新建application.yml下新增mysql的连接信息
# application.yml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysq:10.14.207.135/sell?characterEncoding=utf-8&useSSL=false
  jpa:
    show-sql: true
    database: mysql
server:
  context-path: /sell
#logging:
#  pattern:
##    console: "%d - %msg%n" # 指定控制到输出格式,但日志文件可以看到详细信息
##  path: /var/log/tomcat/   # 指定输出路径
#  file: /var/log/tomcat/sell.log  #指定输出文件
#  level: debug #指定日志级别
#  level:
#    com.dante.imooc.sell.LoggerTest: debug #指定某一类的日志级别
3.创建实体类
首先新建一个  dataobject目录存放所有的实体类,然后新建一个跟数据库表名对应的类。JPA会把驼峰命名法的类名,映射成数据库的 "_" 以此来完成映射。 我们也可以使用@Table(name="")来完成映射。
步骤1. 新建实体类及属性名,对应数据的字段
步骤2. 通过Entity注解声明实体
步骤3. 通过Id声明属性为主键,通过GeneratedValue注明生成策略
步骤4. alt + insert 插入setter and getter
package com.dante.imooc.sell.dataobject;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @Author: Dante
 * @Desciption: 类目表
 * @Date: Created in 2018/1/17 0017 17:30
 * @Nodified By:      in 2018/1/17 0017 17:30
 *
 */
@Table(name="product_category")
@Entity
public class ProductCategory {
    /** 类目id。*/
    @Id
    @GeneratedValue
    private Integer categoryId;

    /**类目名字。*/
    private String categoryName;

    /**类目类型。*/
    private Integer category_type;

    /**类目描述。*/
    private String category_desc;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public Integer getCategory_type() {
        return category_type;
    }

    public void setCategory_type(Integer category_type) {
        this.category_type = category_type;
    }

    public String getCategory_desc() {
        return category_desc;
    }

    public void setCategory_desc(String category_desc) {
        this.category_desc = category_desc;
    }
}

 

参考链接: springBoot常用注解
优化方案:利用lombok插件完成简单的getter,setter,toString方法,然后重写构造方法,注意一定要有一个无参的构造方法。
引入lombok: 
# build.gradle
compile('org.projectlombok:lombok')
//    lombok插件,需要导入,然后IDEA安装Lombok Plugin

 

在实体类中使用@Data注解: 
package com.dante.imooc.sell.dataobject;

import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

/**
 * @Author: Dante
 * @Desciption: 类目表
 * @Date: Created in 2018/1/17 0017 17:30
 * @Nodified By:      in 2018/1/17 0017 17:30
 *
 */
@Table(name="product_category")
@Entity
@DynamicUpdate  //动态更新
@Data           //包含生成getter,setter,和toString
public class ProductCategory {
    /** 类目id。*/
    @Id
    @GeneratedValue
    private Integer categoryId;

    /**类目名字。*/
    private String categoryName;

    /**类目类型。*/
    private Integer categoryType;

    /**类目描述。*/
    private String categoryDesc;

    /**创建时间。*/
    private Date createTime;

    /**更新时间。*/
    private Date updateTime;

    public ProductCategory(String categoryName, Integer categoryType, String categoryDesc) {
        this.categoryName = categoryName;
        this.categoryType = categoryType;
        this.categoryDesc = categoryDesc;
    };

    public ProductCategory() {
    }
}

 

 
4.利用JPA快速构建DAO类,实现对数据库的基本操作
package com.dante.imooc.sell.dataobject;

import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

/**
 * @Author: Dante
 * @Desciption: 类目表
 * @Date: Created in 2018/1/17 0017 17:30
 * @Nodified By:      in 2018/1/17 0017 17:30
 *
 */
@Table(name="product_category")
@Entity
@DynamicUpdate  //动态更新
@Data           //包含生成getter,setter,和toString
public class ProductCategory {
    /** 类目id。*/
    @Id
    @GeneratedValue
    private Integer categoryId;

    /**类目名字。*/
    private String categoryName;

    /**类目类型。*/
    private Integer categoryType;

    /**类目描述。*/
    private String categoryDesc;

    /**创建时间。*/
    private Date createTime;

    /**更新时间。*/
    private Date updateTime;

    public ProductCategory(String categoryName, Integer categoryType, String categoryDesc) {
        this.categoryName = categoryName;
        this.categoryType = categoryType;
        this.categoryDesc = categoryDesc;
    };

    public ProductCategory() {
    }
}

 

 
5.完成对DAO层的单元测试
package com.dante.imooc.sell.dao;

import com.dante.imooc.sell.dataobject.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.transaction.Transactional;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;

/**
 * productCategory接口测试
 * @Author: Dante
 * @Desciption: 测试接口
 * @Date: Created in 2018/1/18 0018 17:18
 * @Nodified By:      in 2018/1/18 0018 17:18
 */
@RunWith(SpringRunner.class)
@SpringBootTest

public class ProductCategoryDaoTest {
    @Autowired
    private ProductCategoryDao dao;

    @Test
    @Transactional
    public void saveTest() {
        ProductCategory productCategory = new ProductCategory("尿素", 2, "尿素,又称碳酰胺(carbamide),是由碳、氮、氧、氢组成的有机化合物是一种白色晶体。最简单的有机化合物之一,是哺乳动物和某些鱼类体内蛋白质代谢分解的主要含氮终产物。也是目前含氮量最高的氮肥。\n" +
                "作为一种中性肥料,尿素适用于各种土壤和植物。它易保存,使用方便,对土壤的破坏作用小,是目前使用量较大的一种化学氮肥。工业上用氨气和二氧化碳在一定条件下合成尿素。");
        ProductCategory result = dao.save(productCategory);
        Assert.assertNotEquals(null, result);
    }
    @Test
    public void modifyTest() {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryId(1);
        productCategory.setCategoryName("复合肥");
        productCategory.setCategoryType(1);
        productCategory.setCategoryDesc("复合肥料是指含有两种或两种以上营养元素的化肥,复合肥具有养分含量高、副成分少且物理性状好等优点,对于平衡施肥,提高肥料利用率,促进作物的高产稳产有着十分重要的作用。\n" +
                "但它也有一些缺点,比如它的养分比例总是固定的,而不同土壤、不同作物所需的营养元素种类、数量和比例是多样的。因此,使用前最好进行测土,了解田间土壤的质地和营养状况,另外也要注意和单元肥料配合施用,才能得到更好的效果。");
        dao.save(productCategory);
    }
    @Test
    public void findOneTest() {
        ProductCategory productCategory = dao.findOne(1);
        System.out.println(productCategory.toString());
    }
    @Test
    public void findByCategoryTypeInTest() {
        List<Integer> list = Arrays.asList(1,2);
        List<ProductCategory> result = dao.findByCategoryTypeIn(list);
        Assert.assertNotNull(result);
    }

}
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

 
 
 
 





相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
10天前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
22 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
22天前
|
缓存 NoSQL Java
Springboot自定义注解+aop实现redis自动清除缓存功能
通过上述步骤,我们不仅实现了一个高度灵活的缓存管理机制,还保证了代码的整洁与可维护性。自定义注解与AOP的结合,让缓存清除逻辑与业务逻辑分离,便于未来的扩展和修改。这种设计模式非常适合需要频繁更新缓存的应用场景,大大提高了开发效率和系统的响应速度。
42 2
|
2月前
|
移动开发 安全 JavaScript
SpringBoot接入微信JSSDK,看这篇妥妥的
这篇教程详细介绍了如何在Spring Boot项目中接入微信JSSDK,实现H5页面的自定义分享和调用相册选取图片等功能。文章首先通过对比理想与现实的分享效果,引出了接入微信JSSDK的必要性。接着,作者提供了GitHub和Gitee上的项目源码链接,并逐步讲解了整个接入过程的关键步骤,包括配置文件、主要类和方法的实现细节,以及必要的微信公众号设置。此外,还特别强调了几个常见问题及其解决方案,如域名绑定、IP白名单设置和签名验证等。最后,通过实际测试验证了功能的正确性。适合初学者快速上手微信JSSDK接入。
46 8
SpringBoot接入微信JSSDK,看这篇妥妥的
|
2月前
|
小程序 JavaScript Java
微信小程序+SpringBoot接入后台服务,接口数据来自后端
这篇文章介绍了如何将微信小程序与SpringBoot后端服务进行数据交互,包括后端接口的编写、小程序获取接口数据的方法,以及数据在小程序中的展示。同时,还涉及到了使用Vue搭建后台管理系统,方便数据的查看和管理。
微信小程序+SpringBoot接入后台服务,接口数据来自后端
|
2月前
|
小程序 安全 Java
|
2月前
|
小程序 Java API
springboot 微信小程序整合websocket,实现发送提醒消息
springboot 微信小程序整合websocket,实现发送提醒消息
|
2月前
|
Java 测试技术 数据库
SpringBoot单元测试快速写法问题之不想在PandoraBoot工程中Mock Dao层如何解决
SpringBoot单元测试快速写法问题之不想在PandoraBoot工程中Mock Dao层如何解决
|
3月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的宠物医院微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的宠物医院微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)
72 7
|
3月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue的宠物医院微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue的宠物医院微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)
81 7
|
3月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的“鼻护灵”微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的“鼻护灵”微信小程序的详细设计和实现(源码+lw+部署文档+讲解等)