當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot微信点餐——实战开发DAO层
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot微信点餐——实战开发DAO层
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
0. 修改grade鏡像,使用阿里云地址,以便于快速加載依賴
參照大佬博客 =====> 阿里云maven鏡像 # 項目目錄下的build.gradlerepositories {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.gradlebuildscript {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.8repositories {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.Driverusername: rootpassword: 123456url: jdbc:mysq:10.14.207.135/sell?characterEncoding=utf-8&useSSL=falsejpa:show-sql: truedatabase: 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@GeneratedValueprivate 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@GeneratedValueprivate 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@GeneratedValueprivate 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) @SpringBootTestpublic class ProductCategoryDaoTest {@Autowiredprivate ProductCategoryDao dao;@Test@Transactionalpublic void saveTest() {ProductCategory productCategory = new ProductCategory("尿素", 2, "尿素,又稱碳酰胺(carbamide),是由碳、氮、氧、氫組成的有機化合物是一種白色晶體。最簡單的有機化合物之一,是哺乳動物和某些魚類體內蛋白質代謝分解的主要含氮終產物。也是目前含氮量最高的氮肥。\n" +"作為一種中性肥料,尿素適用于各種土壤和植物。它易保存,使用方便,對土壤的破壞作用小,是目前使用量較大的一種化學氮肥。工業上用氨氣和二氧化碳在一定條件下合成尿素。");ProductCategory result = dao.save(productCategory);Assert.assertNotEquals(null, result);}@Testpublic void modifyTest() {ProductCategory productCategory = new ProductCategory();productCategory.setCategoryId(1);productCategory.setCategoryName("復合肥");productCategory.setCategoryType(1);productCategory.setCategoryDesc("復合肥料是指含有兩種或兩種以上營養元素的化肥,復合肥具有養分含量高、副成分少且物理性狀好等優點,對于平衡施肥,提高肥料利用率,促進作物的高產穩產有著十分重要的作用。\n" +"但它也有一些缺點,比如它的養分比例總是固定的,而不同土壤、不同作物所需的營養元素種類、數量和比例是多樣的。因此,使用前最好進行測土,了解田間土壤的質地和營養狀況,另外也要注意和單元肥料配合施用,才能得到更好的效果。");dao.save(productCategory);}@Testpublic void findOneTest() {ProductCategory productCategory = dao.findOne(1);System.out.println(productCategory.toString());}@Testpublic 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;">
總結
以上是生活随笔為你收集整理的Spring Boot微信点餐——实战开发DAO层的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 类的组合与封装
- 下一篇: Kotlin难点解析:extension