Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,15 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.h2database:h2'
implementation 'org.jetbrains:annotations:24.0.0'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation 'org.projectlombok:lombok:1.18.26'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// implementation 'org.springframework.boot:spring-boot-starter-jdbc'
}

tasks.named('test') {
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/landvibe/springintro/aop/TimeTraceAop.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package landvibe.springintro.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class TimeTraceAop {
@Around("execution(* landvibe.springintro..*(..))")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
System.out.println("START : " + joinPoint.toString()); // 어떤 메소드를 call 했는 지
try {
return joinPoint.proceed(); // 다음 메소드가 진행
} finally {
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("END : " + joinPoint.toString() + " " + timeMs +
"ms"); // 어떤 메소드를 call 했는지
}
}
}
30 changes: 30 additions & 0 deletions src/main/java/landvibe/springintro/item/config/ItemConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package landvibe.springintro.item.config;
import landvibe.springintro.item.repository.ItemRepository;
import landvibe.springintro.item.service.ItemService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ItemConfig {
/* private final DataSource dataSource;
private final EntityManager em;
@Autowired
public ItemConfig(DataSource dataSource, EntityManager em) {
this.dataSource = dataSource;
this.em = em;
}*/
private final ItemRepository itemRepository;
public ItemConfig(ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@Bean
public ItemService itemService() {
return new ItemService(itemRepository);
}
/* @Bean
public ItemRepository itemRepository() {
// return new MemoryItemRepository();
// return new JdbcItemRepository(dataSource);
// return new JdbcTemplateItemRepository(dataSource);
return new JpaItemRepository(em);
}*/
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package landvibe.springintro.item.controller;

import landvibe.springintro.item.domain.Item;
import landvibe.springintro.item.dto.ItemCreateForm;
import landvibe.springintro.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class ItemController {
private final ItemService service;
@Autowired
public ItemController(ItemService itemService) {
this.service = itemService;
}
@GetMapping("/items/new")
public String createForm(){
return "items/createForm";
}
@PostMapping("/items/new")
public String create(@ModelAttribute ItemCreateForm form) {
Item item = new Item();
item.setName(form.getName());
item.setPrice(form.getPrice());
item.setCount(form.getCount());
service.create(item);
return "redirect:/";
}
@GetMapping("/items")
public String list(Model model){
List<Item> items = service.findItems();
model.addAttribute("items", items);
return "items/itemList";
}
}
20 changes: 20 additions & 0 deletions src/main/java/landvibe/springintro/item/domain/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package landvibe.springintro.item.domain;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer price;
private Integer count;
}
13 changes: 13 additions & 0 deletions src/main/java/landvibe/springintro/item/dto/ItemCreateForm.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package landvibe.springintro.item.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ItemCreateForm {
private String name;
private Integer price;
private Integer count;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package landvibe.springintro.item.repository;

import landvibe.springintro.item.domain.Item;

import java.util.List;
import java.util.Optional;

public interface ItemRepository {

Item save(Item item);
Optional<Item> findById(Long id);
Optional<Item> findByName(String name);
List<Item> findAll();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package landvibe.springintro.item.repository;
import landvibe.springintro.item.domain.Item;
import org.springframework.jdbc.datasource.DataSourceUtils;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class JdbcItemRepository implements ItemRepository {
private final DataSource dataSource;
public JdbcItemRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Item save(Item item) {
String sql = "insert into item(name, price, count) values(?, ?, ?)";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, item.getName());
pstmt.setInt(2, item.getPrice());
pstmt.setInt(3, item.getCount());
pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if (rs.next()) {
item.setId(rs.getLong(1));
} else {
throw new SQLException("id 조회 실패");
}
return item;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public Optional<Item> findById(Long id) {
String sql = "select * from item where id = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
Item item = new Item();
item.setId(rs.getLong("id"));
item.setName(rs.getString("name"));
item.setCount(rs.getInt("count"));
item.setPrice(rs.getInt("price"));
return Optional.of(item);
} else {
return Optional.empty();
}
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public Optional<Item> findByName(String name) {
String sql = "select * from item where name = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
Item item = new Item();
item.setId(rs.getLong("id"));
item.setName(rs.getString("name"));
item.setCount(rs.getInt("count"));
item.setPrice(rs.getInt("price"));
return Optional.of(item);
}
return Optional.empty();
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public List<Item> findAll() {
String sql = "select * from item";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<Item> items = new ArrayList<>();
while (rs.next()) {
Item item = new Item();
item.setId(rs.getLong("id"));
item.setName(rs.getString("name"));
item.setCount(rs.getInt("count"));
item.setPrice(rs.getInt("price"));
items.add(item);
}
return items;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
private void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
close(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package landvibe.springintro.item.repository;
import landvibe.springintro.item.domain.Item;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class JdbcTemplateItemRepository implements ItemRepository {
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateItemRepository(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Item save(Item item) {
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("item").usingGeneratedKeyColumns("id");
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", item.getName());
parameters.put("count", item.getCount());
parameters.put("price", item.getPrice());
Number key = jdbcInsert.executeAndReturnKey(new
MapSqlParameterSource(parameters));
item.setId(key.longValue());
return item;
}
@Override
public Optional<Item> findById(Long id) {
List<Item> result = jdbcTemplate.query("select * from item where id = ? ", rowMapper(), id);
return result.stream().findAny();
}
@Override
public Optional<Item> findByName(String name) {
List<Item> result = jdbcTemplate.query("select * from item where name = ? ", rowMapper(), name);
return result.stream().findAny();
}
@Override
public List<Item> findAll() {
return jdbcTemplate.query("select * from item", rowMapper());
}
private RowMapper<Item> rowMapper() {
return (rs, rowNum) -> {
Item item = new Item();
item.setId(rs.getLong("id"));
item.setName(rs.getString("name"));
item.setPrice(rs.getInt("price"));
item.setCount(rs.getInt("count"));
return item;
};
}
}
Loading