단순 코드 기록/Spring

Spring_MVC_Annotation

일일일코_장민기 2024. 2. 8. 15:33
728x90
Mapper1

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="productMapper">
<select id="selectProduct" resultType="ProductDTO">
select * from t_product
</select>

<select id="selectOrder" resultType="OrderDTO">
select * from t_order
</select>

<update id="productupdate" parameterType="OrderDTO">
update t_product
set quantity = quantity - #{quantity}
where pcode = #{pcode}
</update>

</mapper>

 

 

Mapper2

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="orderMapper">

<insert id="orderInsert" parameterType="com.entity.OrderDTO">
insert into t_order ( num, pcode, quantity )
values ( t_order_seq.nextval, #{pcode} , #{quantity} )
</insert>


</mapper>

 

 

jdbc.properties

 

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=scott
jdbc.passwd=tiger

 

 

DTO1

package com.entity;

import org.apache.ibatis.type.Alias;

@Alias("ProductDTO")
public class ProductDTO {

String pcode;
    String pname;
    int price;
    int quantity;
    
public ProductDTO() {
super();
// TODO Auto-generated constructor stub
}

public String getPcode() {
return pcode;
}

public void setPcode(String pcode) {
this.pcode = pcode;
}

public String getPname() {
return pname;
}

public void setPname(String pname) {
this.pname = pname;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}

@Override
public String toString() {
return "ProductDTO [pcode=" + pcode + ", pname=" + pname + ", price=" + price + ", quantity=" + quantity + "]";
}
    

}

 

 

DTO2

 

 

package com.entity;

import org.apache.ibatis.type.Alias;

@Alias("orderDTO")
public class OrderDTO {

int num;
String pcode;
int quantity;

public OrderDTO() {
super();
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return "OrderDTO [num=" + num + ", pcode=" + pcode + ", quantity=" + quantity + "]";
}

public OrderDTO(int num, String pcode, int quantity) {
super();
this.num = num;
this.pcode = pcode;
this.quantity = quantity;
}

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public String getPcode() {
return pcode;
}

public void setPcode(String pcode) {
this.pcode = pcode;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}


}

 

Main

 

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.dao.ProductDAO;
import com.entity.OrderDTO;
import com.entity.ProductDTO;
import com.service.ProductService;


public class TestMain {

public static void main(String[] args) {

ApplicationContext ctx = new GenericXmlApplicationContext("dept.xml");

ProductService productService = ctx.getBean("productService",ProductService.class);
System.out.println(productService.getDao());

//상품 주문 전, 상품 테이블과 주문 테이블 데이터 확인
System.out.println("주문전 데이터=============================");
List<ProductDTO> list = productService.selectProduct();
for (ProductDTO dto : list) {
System.out.println(dto);
}

System.out.println("order 데이터=======================================");

List<OrderDTO> list2 = productService.selectOrder();
for (OrderDTO dto : list2) {
System.out.println(dto);
}

///////////////// ///////////////// ///////////////// ///////////////// /////////////////

//상품 주문
System.out.println("p01 상품 3개 주문합니다.");
try {
productService.addOrder("p01",3); //add시 문제 발생
} catch (Exception e) {
System.out.println("에러가 발생하여 롤백처리");
}

///////////////// ///////////////// ///////////////// ///////////////// /////////////////

//상품 주문 후, 상품 테이블과 주문 테이블 데이터 확인
System.out.println("주문 후 product table 데이터 =================");
list=productService.selectProduct();
for (OrderDTO dto : list2) {
System.out.println(dto);
}

System.out.println("주문 후 OrderTable 데이터=================");
List<OrderDTO> oList = productService.selectOrder();
for (OrderDTO dto : oList) {
System.out.println(dto);
}

}
}

 

Service

 

package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dao.ProductDAO;
import com.entity.OrderDTO;
import com.entity.ProductDTO;

public class ProductService {

ProductDAO dao;

//Service 함수 시작
public List<ProductDTO> selectProduct(){
return dao.selectProduct();
}

public List<OrderDTO> selectOrder(){
return dao.selectOrder();
}

@Transactional  // tx처리
//필요함수 위에 붙여주면 자동 commit, rollback
public void addOrder(String pcode, int quantity) throws Exception  {
dao.addOrder(pcode,quantity);
}
//Service 함수 끝


///////////////// ///////////////// ///////////////// ///////////////// /////////////////


@Override
public String toString() {
return "ProductService [dao=" + dao + "]";
}

public ProductService() {
super();
// TODO Auto-generated constructor stub
}

public ProductService(ProductDAO dao) {
super();
this.dao = dao;
}

public ProductDAO getDao() {
return dao;
}

public void setDao(ProductDAO dao) {
this.dao = dao;
}


}

 

 

 

DAO

 

 

package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.entity.OrderDTO;
import com.entity.ProductDTO;

public class ProductDAO {

private SqlSessionTemplate template;

///////////////// ///////////////// ///////////////// ///////////////// /////////////////

public ProductDAO() {
super();
System.out.println("DAO호출");
}

public SqlSessionTemplate getTemplate() {
return template;
}

public void setTemplate(SqlSessionTemplate template) {
this.template = template;
}

///////////////// ///////////////// ///////////////// ///////////////// /////////////////


//전체 상품 목록
public List<ProductDTO> selectProduct(){
return template.selectList("selectProduct");
}// end select

//전체 주문 목록
public List<OrderDTO> selectOrder(){
return template.selectList("selectOrder");
}// end select


///////////////// ///////////////// ///////////////// ///////////////// /////////////////

//주문
public void addOrder(String pcode, int quantity) throws Exception{
OrderDTO dto = new OrderDTO();
dto.setPcode(pcode);
dto.setQuantity(quantity);

int n = template.insert("orderMapper.orderInsert", dto);
System.out.println("insert 개수 : " + n); 

//update 수량 감소(쿼리를 잘못 작성해서 에러를 발생시키면 Service의 @Transaction을 통해 자동 롤백)
int n2 = template.update("productMapper.productupdate", dto);
System.out.println("update 개수 : " + n2);
} // end insert
}// class end

 

 

product.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<!-- 0번: annotation 활성화 ****************************************************-->

<!-- 1번: JDBC Properties 등록 ************************************************-->
<context:property-placeholder
location="classpath:com/config/jdbc.properties" />

<!-- 2번: DataSource생성(4가지 정보)(Configuration 역할) **************************-->
<bean id="myDataSource"
class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.userid}"/>
<property name="password" value="${jdbc.passwd}"/>
</bean>

<!-- 2.1번: Tx처리용 TxManager생성 및 txAnnotation 활성화 !!!!!!!!!!!!!!!!!!!!!!!!!!!-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myDataSource"/>
</bean>

<!-- 2.2번: Tx Annotation-driven transaction-manager!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- 3번: SqlSessionFactoryBean 생성 (Configuration 역할) ********************-->
<!-- DataSource / Mapper / Alias 지정 -->
<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mapperLocations">
<list><!-- xml 수만큼 추가 -->
<value>classpath:com/config/orderMapper.xml</value>
<value>classpath:com/config/productMapper.xml</value>
</list>
</property>
<property name="typeAliases">
<list><!-- xml 수만큼 추가 + 3.5 DTO별 Alias 추가!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
<value>com.entity.OrderDTO</value>
<value>com.entity.ProductDTO</value>
</list>
</property>
</bean>

<!-- 4번: SqlSessionTemplate 생성******************************************* -->
<!-- 실제 DAO에서 사용하는 객체(SqlSession과 동일한 기능) -->
<bean id="mySqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="mySqlSessionFactory"/>
</bean>

<!-- 5번: DAO, Service Bean생성 *********************************************-->
<!-- 6번은 메인에서  -->
<bean class="com.dao.ProductDAO" id="productDAO">
<property name="template" ref="mySqlSessionTemplate"/>
</bean>

<bean class="com.service.ProductService" id="productService">
<property name="dao" ref="productDAO"></property>
</bean>



</beans>

'단순 코드 기록 > Spring' 카테고리의 다른 글

Spring_MVC_Repository  (0) 2024.02.08
Spring_MVC_Autowired  (0) 2024.02.08
Spring_MVC  (0) 2024.02.08
Spring_context-scan  (0) 2024.02.08
Spring_SpEL  (0) 2024.02.08