1. MySQL 파일을 작성
CREATE USER 'ecommerceapp'@'localhost' IDENTIFIED BY 'ecommerceapp';
GRANT ALL PRIVILEGES ON * . * TO 'ecommerceapp'@'localhost';
#
# Starting with MySQL 8.0.4, the MySQL team changed the
# default authentication plugin for MySQL server
# from mysql_native_password to caching_sha2_password.
#
# The command below will make the appropriate updates for your user account.
#
# See the MySQL Reference Manual for details:
# https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html
#
ALTER USER 'ecommerceapp'@'localhost' IDENTIFIED WITH mysql_native_password BY 'ecommerceapp';
-- -----------------------------------------------------
-- Schema full-stack-ecommerce
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `full-stack-ecommerce`;
CREATE SCHEMA `full-stack-ecommerce`;
USE `full-stack-ecommerce` ;
-- -----------------------------------------------------
-- Table `full-stack-ecommerce`.`product_category`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `full-stack-ecommerce`.`product_category` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE=InnoDB
AUTO_INCREMENT = 1;
-- -----------------------------------------------------
-- Table `full-stack-ecommerce`.`product`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `full-stack-ecommerce`.`product` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`sku` VARCHAR(255) DEFAULT NULL,
`name` VARCHAR(255) DEFAULT NULL,
`description` VARCHAR(255) DEFAULT NULL,
`unit_price` DECIMAL(13,2) DEFAULT NULL,
`image_url` VARCHAR(255) DEFAULT NULL,
`active` BIT DEFAULT 1,
`units_in_stock` INT(11) DEFAULT NULL,
`date_created` DATETIME(6) DEFAULT NULL,
`last_updated` DATETIME(6) DEFAULT NULL,
`category_id` BIGINT(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_category` (`category_id`),
CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) REFERENCES `product_category` (`id`)
)
ENGINE=InnoDB
AUTO_INCREMENT = 1;
-- -----------------------------------------------------
-- Add sample data
-- -----------------------------------------------------
INSERT INTO product_category(category_name) VALUES ('BOOKS');
INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1000', 'JavaScript - The Fun Parts', 'Learn JavaScript',
'assets/images/products/placeholder.png'
,1,100,19.99,1, NOW());
INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1001', 'Spring Framework Tutorial', 'Learn Spring',
'assets/images/products/placeholder.png'
,1,100,29.99,1, NOW());
INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1002', 'Kubernetes - Deploying Containers', 'Learn Kubernetes',
'assets/images/products/placeholder.png'
,1,100,24.99,1, NOW());
INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1003', 'Internet of Things (IoT) - Getting Started', 'Learn IoT',
'assets/images/products/placeholder.png'
,1,100,29.99,1, NOW());
INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1004', 'The Go Programming Language: A to Z', 'Learn Go',
'assets/images/products/placeholder.png'
,1,100,24.99,1, NOW());
2. Spring boot 파일 생성
- Spring Data JPA
- MySQL Driver
- Rest Repositories
- Lombok
3.IntelliJ에서 Spring boot파일을 Open
4. application.properties 파일 작성
- DB와 Spring Project를 연결하기 위해 필수적으로 작성해준다.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/full-stack-ecommerce?useSSL=false&useUnicode=yes&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=ecommerceapp
spring.datasource.password=ecommerceapp
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.data.rest.base-path=/api
4.entity를 작성한다
- DB에 있는 내용을 JPA를 이용하여 가져온다.
- @Data : lombok사용시 입력해야한다. 그러면 아래 setter,getter을 생략 할 수 있다.
- @Entity : JPA annotation Product DB테이블로 Mapping하기 위해여 사용한다.
- @Table : DB에 Table이름을 입력해준다
- @Id : JPA mapping을 추가한다
- @GeneratedValue(strategy = GenerationType.IDENTITY) : 이 GenerationType은 persistence 공급자가 데이터베이스 ID 열을 사용하여 엔티티에 기본 키를 할당해야 함을 나타낸다.
- @Column(name = "id") : DB의 Column 이름을 작성해준다
-@CreationTimestamp : Hibernate가 자동으로 Timestamps를 관리하게 해준다.
@ManyToOne
@JoinColumn(name = "category_id", nullable = false)
private ProductCategory category;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
이 코드는 Product와 ProductCategory 사이의 관계를 Hibernate를 통해 설정해준다
ManyToOne - OneToMany 관계를 사용하였다.
package com.luv2code.ecommerce.entity;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Table(name="product")
@Data
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "category_id", nullable = false)
private ProductCategory category;
@Column(name = "sku")
private String sku;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "unit_price")
private BigDecimal unitPrice;
@Column(name = "image_url")
private String imageUrl;
@Column(name = "active")
private boolean active;
@Column(name = "units_in_stock")
private int unitsInStock;
@Column(name = "date_created")
@CreationTimestamp
private Date dateCreated;
@Column(name = "last_updated")
@UpdateTimestamp
private Date lastUpdated;
}
package com.luv2code.ecommerce.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name="product_category")
// @Data -- known bug
@Getter
@Setter
public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "category_name")
private String categoryName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Set<Product> products;
}
'Back-end > Spring Framework' 카테고리의 다른 글
Spring boot - Angular Project (2) (0) | 2021.05.07 |
---|---|
JDBC, JPA/Hibernate, Mybatis의 차이 (0) | 2021.05.07 |
Lombok 사용하기 (0) | 2021.05.05 |
Spring boot - Angular Project 시작하기 (0) | 2021.05.05 |
Spring vs. Spring Boot vs. Spring MVC (0) | 2021.03.22 |