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

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;">

 
 
 
 





上一篇:解决生产者-消费者同步问题|学习笔记


下一篇:VSCODE将tab键从四个空格修改为制表符箭头