MySQL
2024. 1. 12. 15:55ㆍSpring Boot
우선
build.gradle에 들어가서
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'mysql:mysql-connector-java:8.0.33'
를 추가해준다
그후
application.properties에
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url= ${sql_url}
spring.datasource.username= ${sql_name}
spring.datasource.password= ${sql_password}
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.format_sql=true
를 추가한다
이때 url, username, password는 본인이 사용 할 mysql 데이터 베이스의 것으로 설정한다
사용할 데이터 형태의 entitiy를 class로 정의한다
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class mySQLEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String title;
@Column
private String data;
mySQLEntity(String title, String data) {
this.title = title;
this.data = data;
}
}
따로 설정을 하지 않아도 JpaRepository를 상속받으면 기본적인 작업은 query를 따로 설정하지 않고 가능하다
package com.example.demo.mySQL;
import org.springframework.data.jpa.repository.JpaRepository;
public interface mySQLRepository extends JpaRepository<mySQLEntity, Long> {
}
controller에서 직접 데이터를 다루지 않도록 repository를 받아서 작업을 하는 service를 만든다
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class mySQLService {
@Autowired
private final mySQLRepository repo;
public void create_data(String title, String data) {
repo.save(new mySQLEntity(title, data));
}
public List<mySQLEntity> all_data() {
return repo.findAll();
}
public mySQLEntity update_data(Long id, String title, String data) {
Optional<mySQLEntity> tmp = repo.findById(id);
if(tmp != null) {
mySQLEntity test = tmp.get();
if(title != null) {
test.setTitle(title);
}
if(data != null)
test.setData(data);
repo.save(test);
return test;
}
return null;
}
public void delete_data(Long id) {
repo.deleteById(id);
}
public Optional<mySQLEntity> get_data(Long id) {
return repo.findById(id);
}
}
'Spring Boot' 카테고리의 다른 글
| MongoDB Reference (1) | 2024.01.19 |
|---|---|
| Https (0) | 2024.01.12 |
| Json Web Token (2) | 2024.01.02 |
| CustomFilter (0) | 2024.01.02 |
| SecurityFilterChain (0) | 2024.01.02 |