SpringBoot学习随笔记录3(mysql配置、MVC-DAO、lombok)

mysql配置
1.项目添加mysql依赖,配置操作数据库包


WechatIMG1.jpeg
   <!-- 添加mysql依赖       -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--   使用 starter-data-jpa操作数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

2.把xx/src/main/resources/下的 application.properties改名为application.yml,因为yml使代码更加简洁。
application.yml中配置数据库内容

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver   #设置数据库驱动
    username: root                             #用户名
    password: 123456                           #密码
    url: jdbc:mysql://192.168.1.137/sell?characterEncoding=utf-8&useSSL=false  #数据库地址,characterEncoding防止中文乱码,useSSL忽略非SSL安全协议警告
  jpa:
    show-sql: true            #因为是开发环境所以打印sql语句

MVC架构:DAO-service-Controller
MVC - DAO要点:
a.数据库表名和项目中类名关系


屏幕快照 2019-04-04 下午5.05.23.png

虽然类名驼峰写,表名是下划线写法,但是spring-boot-starter-data-jpa会自动识别将两者关联
如果想类名与表名不一致可以这样写:


WechatIMG2.jpeg
  b.数据库映射成对象需要在类中加上@Entity注解
  c.@Id   //主键.    @GeneratedValue   //自增,   command+n设置get/set/toString方法

单元测试

  1. 选中接口右键->Go to->Test, create new test
    2.Springboot2.0后findOne(id)方法被废除,使用findById(id).get()代替, findOne(S)用来查找对象S
    3.repository.save(productCategory);增加数据时,如果不设置id,使用自增id,直接保存会报错。需要在自增id注解中加 strategy = GenerationType.IDENTITY,如:@GeneratedValue(strategy = GenerationType.IDENTITY) //自增
    4.自动更新时间需要在表类中添加@DynamicUpdate注解(否则表类中有createTime、updateTime属性时,更新方法不会自动更新时间)
    5.添加构造方法,command+n -> Constructor
    6.@Transactional注解可以是测试内容不插入表中
    @Test
    @Transactional //设置测试内容不插入表中
    public void testTest(){
        //构造方法添加数据
        ProductCategory productCategory = new ProductCategory("老人最爱",4);
        ProductCategory result = repository.save(productCategory);
        Assert.assertNotNull(result);//不为空表示成功
    }

7.list条件查询,ProductCategoryRepository接口添加

public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {

    //list查询,一次查多个数据,查的结果为list,通过CategoryType查,In代表在其范围内的,查询条件为categoryTypeList。即:查询CategoryType在categoryTypeList范围内的数据
    List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}

注意:使用list条件查询时需要有一个无参的构造方法

lombok插件使用
lombok以简单的注解形式来简化java代码,提高开发人员的开发效率,如生成构造器、getter/setter、equals、hashcode、toString等等
使用方法:pom.xml添加依赖

        <!--lombok以简单的注解形式来简化java代码,提高开发人员的开发效率,如生成构造器、getter/setter、equals、hashcode、toString等等-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

( IDEA需要添加下载插件:
preferences->搜索Plugins->搜索lombok->安装)
*使用时需要在表类中加注解@Data ,@Data包含了getter/setter、equals、hashcode、toString等等方法。

表类:

package com.gang.sell.dataobject;

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

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

/*
*类目
*
**/
@Entity
@DynamicUpdate
@Data
public class ProductCategory {

    /* 类目id */
    @Id   //主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)   //自增
    private  Integer categoryId;

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

    /* 类目编号 */
    private  Integer categoryType;

//    private Date createTime;
//
//    private Date updateTime;


    //    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 getCategoryType() {
//        return categoryType;
//    }
//
//    public void setCategoryType(Integer categoryType) {
//        this.categoryType = categoryType;
//    }
//
//    public Date getCreateTime() {
//        return createTime;
//    }
//
//    public void setCreateTime(Date createTime) {
//        this.createTime = createTime;
//    }
//
//    public Date getUpdateTime() {
//        return updateTime;
//    }
//
//    public void setUpdateTime(Date updateTime) {
//        this.updateTime = updateTime;
//    }
//
//    @Override
//    public String toString() {
//        return "ProductCategory{" +
//                "categoryId=" + categoryId +
//                ", categoryName='" + categoryName + '\'' +
//                ", categoryType=" + categoryType +
//                '}';
//    }

    //构造方法

    //无参构造方法
    public ProductCategory() {
    }

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

接口类:

package com.gang.sell.repository;

import com.gang.sell.dataobject.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {

    //list查询,一次查多个数据,查的结果为list,通过CategoryType查,In代表在其范围内的,查询条件为categoryTypeList。即:查询CategoryType在categoryTypeList范围内的数据
    List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}

测试类:

package com.gang.sell.repository;

import com.gang.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.sql.Array;
import java.util.Arrays;
import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest {

    @Autowired
    private  ProductCategoryRepository repository;

    @Test
    public void findOneTest() {
        ProductCategory productCategory = repository.findById(1).get();
        System.out.println(productCategory.toString());
    }

    @Test
    public void saveTest() {//新增数据
        //1
//        //增加数据时,如果不设置id,使用自增id,直接保存会报错。需要在自增id注解中加    strategy = GenerationType.IDENTITY
//        ProductCategory productCategory = new ProductCategory();
//        productCategory.setCategoryName("女生最爱");
//        productCategory.setCategoryType(3);
//        repository.save(productCategory);


        //2
        //构造方法添加数据
        ProductCategory productCategory = new ProductCategory("女生最爱",3);
        ProductCategory result = repository.save(productCategory);
        Assert.assertNotNull(result);//不为空表示成功
//      等价于  Assert.assertNotEquals(null,result);
    }

    @Test
    public void updateTest(){//更新数据
        //1
//        ProductCategory productCategory = new ProductCategory();
//        productCategory.setCategoryId(2); //更新数据需要设置id
//        productCategory.setCategoryName("男生最爱");
//        productCategory.setCategoryType(3);
//        repository.save(productCategory);
        //2
        //查数据
        ProductCategory productCategory = repository.findById(2).get();
        //改数据
        productCategory.setCategoryType(9);
        //保存
        repository.save(productCategory);

    }

    @Test
    @Transactional //设置测试内容不插入表中
    public void testTest(){
        //构造方法添加数据
        ProductCategory productCategory = new ProductCategory("老人最爱",4);
        ProductCategory result = repository.save(productCategory);
        Assert.assertNotNull(result);//不为空表示成功
    }


    @Test
    //条件查询
    public void findByCategoryTypeInTest(){
        List<Integer> list = Arrays.asList(2,3,4);//CategoryType为2或3或4的数据
        List<ProductCategory> result = repository.findByCategoryTypeIn(list);
        Assert.assertNotEquals(0,result.size()); //查出结果大于0

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容

  • jHipster - 微服务搭建 CC_简书[//www.greatytc.com/u/be0d56c4...
    quanjj阅读 812评论 0 2
  • JSPXCMS开发架构介绍 V1 – 架构概述 基本概述 配置文件目录 /src/main/resources/...
    Java_Evan阅读 4,390评论 0 0
  • springboot 概述 SpringBoot能够快速开发,简化部署,适用于微服务 参考嘟嘟大神SpringBo...
    一纸砚白阅读 5,424评论 2 20
  • 这个冬夜,窗外的温度零下十几度,屋内却温暖如春。 2017年的旅程就要结束了,我们即将踏上2018年的新征程。 这...
    流年芳华阅读 506评论 0 6
  • 大学四年一晃而逝,大抵只有到了毕业的时候才会觉得四年如此短暂。所遇到的人,所经历的事,就像过电影一样在脑海中闪现,...
    浮生万绪阅读 271评论 0 0