
코딩애플 강의를 통해 배운 Spring Boot & JPA를 정리한 글입니다.
2025년 3월 06일
Part 1 : Part 1
# Run
ShopApplication
# 웹 실행 (8080이기본)
http://localhost:8080/
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
Friend friend = new Friend("nam",12);
System.out.println(friend.name + ' ' + friend.age);
}
}
class Friend {
// field, attribute
String name ="kim";
int age = 20;
// constructor
Friend(String name, int age){
this.name = name;
this.age = age;
}
// method
void hello() {
System.out.println("ㅎㅇ");
}
}
@Controller를 붙이면 알아서 main함수에서 실행이됨@ResponseBody를 붙이면 문자 그대로 보내주세요 라는 뜻// 문자를 return
public class BasicController {
@GetMapping("/")
@ResponseBody
String hello() {
return "안녕하세요";
}
}
// html을 return
public class BasicController {
@GetMapping("/")
String hello() {
return "index.html";
}
}
build.gradle 파일에서 설치dependencies에 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'입력@Controller
public class ItemController {
@GetMapping("/list")
String list (Model model) {
model.addAttribute("전달할데이터이름", "데이터");
return "list.html";
}
}
<!-- 전달받은 데이터를 적용 -->
<div>
<h4 th:text="${name}"></h4>
</div>
# gradle
runtimeOnly 'com.mysql:mysql-connector-j' # mysql접속을 도와줌
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' # ORM라이브러리
# application properties
spring.datasource.url=jdbc:mysql://localhost:3306/shop
spring.datasource.username=root
spring.datasource.password=ska980630@
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.hibernate.ddl-auto=update
// Item
public class Item {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
@Column(nullable = false, unique = true)
@Column(columnDefinition = "Text")
@Column(length = 1000)
public String title;
public Integer price;
}
# gradle
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
# setting
annotation processors
Enable annotation processing 체크
plugin lombok 다운
//interface
public interface ItemRepository extends JpaRepository<Item, Long> {
}
//Controller
@Controller
@RequiredArgsConstructor
public class ItemController {
private final ItemRepository itemRepository;
@GetMapping("/list")
String list (Model model) {
List<Item> result = itemRepository.findAll();
System.out.println(result.get(0));
model.addAttribute("name", "홍길동");
return "list.html";
}
}
<div class="card" th:each="items : ${items}">
<img src="https://placehold.co/300" />
<div>
<h4 th:text="${items.title}">바지</h4>
<p th:text="${items.price}">7억</p>
</div>
</div>
Entity파일에서 @ToString 선언해준다
Controller파일에서 System.out.println(result.toString()); 선언
private String title = 'test'
// getter
public String getTitle() {
return title;
}
// setter
public void setTitle(String title) {
this.title = title;
}
or
@Getter
@Setter
public class Item {
private String title = 'test'
}