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

来自为知笔记(Wiz)

原文地址:https://www.cnblogs.com/DDante/p/a37bb4bf4f537e28085a88614045a68b.html

时间: 2024-08-02 19:55:01

Spring Boot微信点餐——实战开发DAO层的相关文章

Spring boot微信点餐系统学习笔记

说起java,大学的时候自学了两个月就放弃了,转而学习C++,现在毕业才发现很多好的想法,从策划到具体实现,都要根据自身能力来挑选框架,进而学习语言,熟练使用C++后去学习其他的语言那才是轻车熟路,基本上两个月就能掌握,毕竟事物是普遍存在联系性的. 学习Spring Boot先要从Spring MVC说起,刚开始接触spring mvc,个人赶紧它对XML的依赖太大,然而,配置XML是一件痛苦的事,对于我来说.boot是最佳选择,干净利落,让人专注于业务的逻辑现实,而不用写一堆配置.一堆XML配

Spring Boot微信点餐——数据库设计

数据库设计: 具体代码如下: create table `product_info` ( `product_id` varchar(32) not null comment '商品ID', `product_name` varchar(64) not null comment '商品名称', `product_price` decimal(10,2) not null comment '商品单价', `product_stock` int not null comment '库存', `prod

第二章-spring boot springDataJPA快速开发DAO层,junit测试

一.简介 第一章介绍了spring boot简单入门,这一章介绍一下如何通过springDataJPA快速实现DAO层开发. 二.环境 1. jdk1.8 2. springboot 1.5.9.RELEASE 3. apache maven(3.5.0) 4. 开发工具(IntelliJ IDEA ) 三.步骤 1)通过idea file->new project->Spring Initializr 创建项目,选中web->web,sql->JPA.MySQL.       

基于Springboot+SpringCloud的微信点餐系统开发视频教程

基于Springboot+SpringCloud的微信点餐系统开发视频教程课程分享链接:https://pan.baidu.com/s/1q7h9zn8sGf_e0k38pc69tw 密码:fk9w 随着互联网不断发展,大家的生活习惯也不断在改变,像美团,饿了么平台的外卖快速的发展起来,这就是我们所说的O2O,即线上和线下结合同时微信也给人们带来了沟通的便利,现在几乎每个年轻人都会有微信号,所以我们开发微信点餐系统,也是极大方便了大家的使用,只要在打开微信进入我们的点餐系统就可以方便的进行点餐.

spring boot + vue + element-ui全栈开发入门——开篇

最近经常看到很多java程序员朋友还在使用Spring 3.x,Spring MVC(struts),JSP.jQuery等这样传统技术.其实,我并不认为这些传统技术不好,而我想表达的是,技术的新旧程度体现了做项目时的生产力.生产力低了,项目的开发成本就高.反之,生产力高,则成本低.笔者写本系列的目的是让使用“前后端不分离”的老技术的开发者做一个入门级的过度.因为目前流行的“前后端分离”技术足够简单,足够方便,足够易学,也足够完善. 项目所使用的前端技术是:element-ui,文档地址是:ht

spring boot + vue + element-ui全栈开发入门——基于Electron桌面应用开发

 前言 Electron是由Github开发,用HTML,CSS和JavaScript来构建跨平台桌面应用程序的一个开源库. Electron通过将Chromium和Node.js合并到同一个运行时环境中,并将其打包为Mac,Windows和Linux系统下的应用来实现这一目的. Electron于2013年作为构建Github上可编程的文本编辑器Atom的框架而被开发出来.这两个项目在2014春季开源. 目前它已成为开源开发者.初创企业和老牌公司常用的开发工具. 看看谁在使用Electron

【课程分享】深入浅出微信公众平台实战开发(微网站、LBS云、Api接口调用、服务号高级接口)

深入浅出微信公众平台实战开发(微网站.LBS云.Api接口调用.服务号高级接口) 课程下载地址:链接:http://pan.baidu.com/share/link?shareid=2214724072&uk=3611155194 密码:glvc 一.本课程是怎么样的一门课程(全面介绍) 1.1.课程的背景 微信公众平台的火热程度已经不用多言,无论是个人还是企业,政府还是商家,都已经开始搭建微信公众平台,微信的作用已经被各界人士认可.微信公众平台的技术需求市场缺口巨大. 1.2.课程内容简介 本

Spring框架之使用JdbcTemplate开发Dao层程序

简介: JdbcTemplate开发dao层程序     由Spring框架给我们提供,Spring提供的很多操作数据源(关系型数据库,二维表格模型,有明确的行和列(mysql/orcal等) 非关系型数据库(redis.mongodb)NoSQL)消息列(activeMq,jms)的小工具 JdbcTemplate操作关系数据库 RedisTemplate操作redis JmsTtemplate操作消息队列 JdbcTemplate类 使用方法和QueryRunner基本一致. 构造方法传递数

框架 day65 Mybatis入门(基础知识:框架原理,入门[curd],开发dao层,全局与映射配置)

Mybatis 基础知识(一) 第一天:基础知识(重点) mybatis介绍 mybatis框架原理(掌握) mybaits入门程序(掌握) 用户信息进行增.删.改.查 mybatis开发dao层方法:(掌握) 原始dao开发方法(dao接口和实现类需要程序员编写) mapper代理开发方法(程序员只需要编写接口) SqlMapConfig.xml(mybatis全局配置文件)(掌握) mybatis输入映射(掌握) mybatis输出映射(掌握) mybatis动态sql(掌握)   1