Spring(baek)

2021-12-09 Controller12 method01~method10

Hesitater 2021. 12. 8. 19:23
728x90

 

org.zerock.controller.p05controller 에 Controller12

org.zerock.mapper.p05mapper 에 Mapper03.java

org.zerock.mapper.p05mapper 에 Mapper03.xml

 

 

전체 코드

 

Controller12

더보기
package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.controller.p05controller.bean.Bean17;
import org.zerock.controller.p05controller.bean.Bean18;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met01")
	public void method01() {
		String customerName = "ironman";
		String contactName = "tony";
		
//		mapper.insertCustomer(customerName, contactName);
		int cnt = mapper.insertCustomer(customerName, contactName);
		System.out.println(cnt);
		
	}
	
	@RequestMapping("/met02")
	public void method02() {
		String supplierName = "captain";
		String contactName = "steve";
		
		int cnt = mapper.insertSupplier(supplierName, contactName);
		System.out.println(cnt);
		
	}
	
	@RequestMapping("/met03")
	public void method03() {
		// 2. request 분석, 가공
		Bean17 bean = new Bean17();
		bean.setCustomerName("spiderman");
		bean.setContactName("peter");
		bean.setAddress("queens");
		bean.setCity("ny");
		bean.setPostalCode("2222");
		bean.setCountry("usa");
		
		// 3. business logic( 주로 db작업)
		mapper.insertCustomer2(bean);
		
		// 4. setattribute
		
		
		// 5. forward/ redirect
	}
	
	@RequestMapping("/met04")
	public void method04() {
		// 2. bean 작성(Bean18 by Suppliers)
		Bean18 bean = new Bean18();
		bean.setSupplierName("Thor");
		bean.setContactName("Ham");
		bean.setAddress("Nornheim");
		bean.setCity("Valhala");
		bean.setPostalCode("20171025");
		bean.setCountry("Asgard");
		bean.setPhone("010-1234-5678");
		
		// 3. mapper 실행
		mapper.insertSupplier2(bean);
	}
	
	
	@RequestMapping("/met05")
	public void method05( ) {
		// 2. request 분석, 가공
		Bean17 bean = new Bean17();
		bean.setCustomerName("danvers");
		bean.setContactName("marvel");
		bean.setAddress("seoul");
		bean.setCity("gangnam");
		bean.setPostalCode("9999");
		bean.setCountry("france");
		
		// 3. insert 하기전 id
		System.out.println(bean.getId()); // null or 0
		
		
		mapper.insertCustomer3(bean);
		
		System.out.println(bean.getId()); //인서트 한이후 key
		
	}
	
	
	@RequestMapping("/met06")
	public void method06() {
		// 2.
		Bean18 bean = new Bean18();
		bean.setSupplierName("wade");
		bean.setContactName("deadpool");
		bean.setAddress("yeoksam");
		bean.setCity("seoul");
		bean.setPostalCode("3333");
		bean.setCountry("UK");
		bean.setPhone("111");
		
		// 3. mapper 실행
		System.out.println(bean.getSupplierID());  // null or 0
		
		mapper.insertSupplier3(bean);
		
		System.out.println(bean.getSupplierID());  // key
	}
	
	
	@RequestMapping("/met07")
	public void method07() {
		// 2
		Bean17 bean = new Bean17();
		bean.setId(111);
		bean.setCustomerName("widow");
		bean.setContactName("nat");
		bean.setAddress("jongro");
		bean.setCity("Asgard");
		bean.setCountry("korea");
		bean.setPostalCode("77777");
		// 3
		int cnt = mapper.updateCustomer(bean);
		System.out.println(cnt);
	}
	
	
	// TODO : update Supplier
	@RequestMapping("/met08")
	public void method08() {
		// 2 request 가공 분석?
		Bean18 bean18 = new Bean18();
		bean18.setSupplierID(45);
		bean18.setSupplierName("Anastasiya");
		bean18.setContactName("NikolaYevna");
		bean18.setAddress("Don");
		bean18.setCity("Rostov");
		bean18.setPostalCode("863");
		bean18.setCountry("russia");
		bean18.setPhone("1119875");
		
		
		// 3.
		int cnt = mapper.updateSupplier(bean18);
		System.out.println(cnt); //성공 여부 
		
	}
	
	@RequestMapping("/met09")
	public void method09(Integer id) {
		int cnt = mapper.deleteCustomer(id);
		
		System.out.println(cnt);  // cnt  가 1인지 아닌지 에따라 따른 구문으로 처리해줘야함
	}
	
	@RequestMapping("/met10")
	public void method10(Integer id) {
		int cnt = mapper.deleteSuppliers(id);
		
		System.out.println(cnt);  // cnt  가 1인지 아닌지 에따라 따른 구문으로 처리해줘야함
		
	}
	
}

Mapper03

더보기
package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;
import org.zerock.controller.p05controller.bean.Bean17;
import org.zerock.controller.p05controller.bean.Bean18;

public interface Mapper03 {

	//method01
	public int insertCustomer(@Param("customerName") String customerName,
				@Param("contactName") String contactName);
		
	//method02
	public int insertSupplier(@Param("supplierName") String supplierName,
				@Param("contactName") String contactName);
	
	//method03
	public int insertCustomer2(Bean17 bean);

	//method04
	public int insertSupplier2(Bean18 bean);

	//method05
	public int insertCustomer3(Bean17 bean);

	//method06
	public int insertSupplier3(Bean18 bean);
	
	//method07
	public int updateCustomer(Bean17 bean);

	//method08
	public int updateSupplier(Bean18 bean18);
	
	
	//method09
	public int deleteCustomer(Integer id);

	//method10
	public int deleteSuppliers(Integer id);
	
	
	
	
	//method11
	
	
	
	//method12
	
}


Mapper03.xml

더보기
<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">
	
	<!-- method01 -->
	<insert id="insertCustomer">
	INSERT INTO Customers (CustomerName, ContactName)
	VALUES (#{customerName}, #{contactName})
	</insert>
	
	<!-- method02 -->
	<insert id="insertSupplier">
	INSERT INTO Suppliers (SupplierName, ContactName)
	VALUES (#{supplierName}, #{contactName})
	</insert>
	
	<!-- method03 -->
	<insert id="insertCustomer2">
		INSERT INTO Customers (CustomerName, ContactName, Address, PostalCode, Country, City)
		VALUES (#{customerName}, #{contactName}, #{address}, #{postalCode}, #{country}, #{city} )
<!--VALUES (#{bean.customerName}, #{bean.contantName}, #{bean.address}, #{bean.postalCode}, #{bean.country}, #{bean.city} )  -->		
	</insert>

	<!-- method04 -->
	<insert id="insertSupplier2">
		INSERT INTO Suppliers (SupplierName, ContactName, Address, City, PostalCode, Country, Phone)
		VALUES (#{supplierName}, #{contactName}, #{address}, #{city}, #{postalCode}, #{country}, #{phone} )
	</insert>


	<!-- method05 -->
	<insert id="insertCustomer3" useGeneratedKeys="true" keyProperty="id" keyColumn="customerID">
	INSERT INTO Customers (CustomerName, ContactName, Address, PostalCode, Country, City)
	VALUES (#{customerName}, #{contactName}, #{address}, #{postalCode}, #{country}, #{city} )

	
	</insert>

	<!-- method06 -->
	<insert id="insertSupplier3" useGeneratedKeys="true" keyProperty="supplierID" keyColumn="SupplierID">
	INSERT INTO Suppliers (SupplierName, ContactName, Address, City, PostalCode, Country, Phone)
	VALUE (#{supplierName}, #{contactName}, #{address}, #{city}, #{postalCode}, #{country}, #{phone} )
	
	</insert>

	<!-- method07 -->
	<update id="updateCustomer">
	UPDATE Customers
	SET
		CustomerName = #{customerName},
		ContactName = #{contactName},
		Address= #{address},
		City = #{city},
		PostalCode = #{postalCode},
		Country = #{country}
	WHERE
		CuStomerID = #{id}	
	</update>

	<!-- method08 -->
	<update id="updateSupplier">
	UpDATE Suppliers
	SET
		SupplierName = #{supplierName},
		ContactName = #{contactName},
		Address = #{address},
		City = #{city},
		PostalCode = #{postalCode},
		Country = #{country},
		Phone = #{phone}
	WHERE	
		SupplierID = #{SupplierID}
	</update>

	<!--delete  method09  -->
	<delete id="deleteCustomer">
	DELETE FROM Customers WHERE CustomerID = #{id}
	
	</delete>
	
		
	<!-- method010 -->
	<delete id="deleteSuppliers">
	DELETE FROM Suppliers WHERE SupplierID = #{id}
	</delete>


	<!-- method011 -->


	<!-- method012 -->


	<!-- method013 -->


	<!-- method014 -->


</mapper>

<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

 

교재 164쪽~267쪽

 

 

 

현 데이터 자료(테이블구성)가 조금식 다를 수 있음

 

전날에는 SELECT 로 조회 위주였다면

 

 Customers, Suppliers 테이블에 각각 insert, update, delete 를 해보는것같다.

 

★Controller12의 method01

 

Customers 테이블의 customerName, contactName 만 받아서 입력 

Mapper03에서 2개의 파라미터가 있으면 xml에서 순서대로 찾아서 쓸수 있지만

이름을 명시해주는것이 코드를 읽기  간편하니 @Param("customer") , @Param("contactName") 과같이

@Param 어노테이션으로 어떤 이름으로 xml에서 사용되는지 명시해주는게 좋음

 

 

리턴타입이 int인 이유

예전에는 Servletjsp에서 그냥 JDBC를 가공없이 사용했을때에는 ? 를 넣어서 사용했다 그떄 사용했던 메소드가

Interface PreparedStatement  에  executeUpdate() 라는 메소드를 실행시켰다.

(INSERT, UPDATE, DELETE 쿼리를 날릴때 사용했다 이 메소드의 리턴 타입이 int이다)

 

INSERT, UPDATE 또는 DELETE와 같은 SQL Data Manipulation Language(DML) 문 또는 DDL 문과 같이 아무 것도 반환하지 않는 SQL 문이어야 하는 이 PreparedStatement 개체의 SQL 문을 실행합니다.

 

여기서 리턴타입 int가 무슨 의미 이냐면  영향을 미친 행의 개수이다. 

예를들어 한개를 넣으면 1이 리턴, 1개를 업데이트하면 1이 리턴, .. 몇개의 레코드가 영향을 받게됬는지

int로 명시해주면 그 값을 리턴해준다.

 

 

 

 

Controller12 의 method01

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met01")
	public void method01() {
		String customerName = "ironman";
		String contactName = "tony";
		
//		mapper.insertCustomer(customerName, contactName);
		int cnt = mapper.insertCustomer(customerName, contactName);
		System.out.println(cnt);
		
	}
	
}

 

 

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	public int insertCustomer(@Param("customerName") String customerName,
			@Param("contactName") String contactName);
		
}

 

 

 

Mapper03.xml

insert쿼리를 날리는거니깐 <insert>태그가 필요

id에 메소드명, 값은 파람어노테이션으로 넣은 이름으로 #{customerName}, #{contactName }

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

<!--method01  -->
<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<insert id="insertCustomer">
	INSERT INTO Customers (CustomerName, ContactName)
	VALUES (#{customerName}, #{contactName})
	
	</insert>


</mapper>

각각 매치되는것들 화살표

 

○결과값

요청하기전 Customers 테이블의 자료

 

 

http://localhost:8080/controller/cont12/met01 요청시

108번으로 잘 인서트 되었음

 

 

 

 

 

 

 

 

★Controller12의 method02

 

Suppliers 테이블에 새로운 레코드 입력, supplierName, contactName 만

xml 에서 id에 메소드명과 같은걸 넣고

 

insert는  resultType가 필요가 없다. 왜냐하면 select 해오는 경우는 무엇을 담을 bean, string 이 필요한데

insert는 몇개의 레코드에 영향에 미쳤는지 값만 리턴이 되기 때문에, 실제 실행하는 메소드가 executeUpdate이기때문에 int값만 리턴되어서 resultType를 명시해줄 필요가없다.

 

Controller12 의 method02

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met02")
	public void method02() {
		String supplierName = "captain";
		String contactName = "steve";
		
		int cnt = mapper.insertSupplier(supplierName, contactName);
		System.out.println(cnt);
		
	}
	
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	public int insertSupplier(@Param("supplierName") String supplierName,
				@Param("contactName") String contactName);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

<!--method02  -->
<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<insert id="insertSupplier">
	INSERT INTO Suppliers (SupplierName, ContactName)
	VALUES (#{supplierName}, #{contactName})
	
	</insert>


</mapper>

○결과값

 

요청하기전 Supplier테이블자료

 

http://localhost:8080/controller/cont12/met02 요청시 

43번 추가 확인

 

 

 

 

--

하나의 레코드에 2개정보만 넣으면 위에 처럼 가능하다

interface Mapper03 에

public int insertCustomer(customerName, contactName, city, address, country, poastal code);

이런식으로 작성할 수 있는데 너무 지저분한 메소드가 되어 보인다.

이렇게 작성하는건 좋은 방법이 아니다 

그래서 이런 값들을 가지고있는 bean(DTO - Data Transfer Object 라는 이름을쓴다)을 넘겨주는게 좋다

 

 

 

 

 

★Controller12의 method03

 

DTO 

값들을 가지고 있는 빈을 넘겨주는게 낫다

Bean17에 때려 박고 Bean17을 넘겨준다.


Bean17
Customers 테이블 컬럼들

메서드는 파라미터 순서가  bean은 파라미터 하나인데  bean안에 프로퍼티가 여러개(여기서는7개) 있다 
get머머머 메소드가 7개 있다. CustomerId는 자동증가라 뺴고

bean의 프로퍼티 쓰듯이 (jsp에서 ${}처럼) #{ }로 사용하면 된다.

 

Mapper03.xml에서


우리가 넣은건 파라미터 bean 하나 인데
.getBean(); 을 실행시키려고 하였다.

우리는 파라미터의 명칭을 사용하지 말고 프로퍼티명만 쓰면된다. 

( bean.customerName 이아니라 customerName 이런식으로)

get머머의 프로퍼티를 실행시켜주면된다 Mapper03.xml 에서 쿼리 입력시
VALUES (#{bean.customerName}, #{bean.contantName}, #{bean.address}, #{bean.postalCode}, #{bean.country}, #{bean.city} )가 아니고


VALUES (#{customerName}, #{contactName}, #{address}, #{postalCode}, #{country}, #{city} ) 이다.

CustomerId는 자동 증가라 안 넣어도됨

 

 

Controller12 의 method03

id는 유일해야해서 method01에서 insertCustomer를 사용해서 method03에서는 id 값을 insertCustomer2를 사용

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met03")
	public void method03() {
		// 2. request 분석, 가공
		Bean17 bean = new Bean17();
		bean.setCustomerName("spiderman");
		bean.setContactName("peter");
		bean.setAddress("queens");
		bean.setCity("ny");
		bean.setPostalCode("2222");
		bean.setCountry("usa");
		
		// 3. business logic( 주로 db작업)
		mapper.insertCustomer2(bean);
		
		// 4. setattribute
		
		
		// 5. forward/ redirect
	}
	
}

Bean17

package org.zerock.controller.p05controller.bean;

import lombok.Data;

@Data
public class Bean17 {

		private Integer customerID;
		private String customerName;
		private String contactName;
		private String city;
		private String address;
		private String postalCode;
		private String country;
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method03
	public int insertCustomer2(Bean17 bean);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method03 -->
	<insert id="insertCustomer2">
		INSERT INTO Customers (CustomerName, ContactName, Address, PostalCode, Country, City)
		VALUES (#{customerName}, #{contactName}, #{address}, #{postalCode}, #{country}, #{city} )
<!--VALUES (#{bean.customerName}, #{bean.contantName}, #{bean.address}, #{bean.postalCode}, #{bean.country}, #{bean.city} )  -->		
	</insert>


</mapper>

○결과값

요청전 Customers 테이블정보

 

http://localhost:8080/controller/cont12/met03 요청시

111 번째로 들어감

 

 

 

 

 

 

 

★Controller12의 method04

Mapper03.xml에서 

프로퍼티 작성시 #{ } 을 사용해야함

jsp에서 했던것처럼 ${} 로 혼동하면 안되용....ㅠ 

 

Bean18클래스만들어야하고 insertSupplier2메소드 만들어야하고 메소드에 해당하는 xml코드수정

// 2. 에서

Bean18을 만들어서 프로퍼티를 세팅하고 그것을 mapper.insertCustomer2(bean); 으로 넣어주고

insertCustomer2 메서드를 만든다( ctrl+1로 힌트얻어서) 그다음 xml에 insertSupplier2의 id를가진 <insert>가 존재하면된다 

SupplierID 는 자동 증가라 안 넣어도됨

 

여기서 나중에  // 03 에서 몇개받았는지 잘 받아서 1개면 잘 들어간거니 어디로 forward 하고

0이면 잘못들어온거니 어디로 forward하고..?

 

Controller12 의 method04

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met04")
	public void method04() {
		// 2. bean 작성(Bean18 by Suppliers)
		Bean18 bean = new Bean18();
		bean.setSupplierName("Thor");
		bean.setContactName("Ham");
		bean.setAddress("Nornheim");
		bean.setCity("Valhala");
		bean.setPostalCode("20171025");
		bean.setCountry("Asgard");
		bean.setPhone("010-1234-5678");
		
		// 3. mapper 실행
		mapper.insertSupplier2(bean);
	}
	
}

 

Bean18

package org.zerock.controller.p05controller.bean;

import lombok.Data;

@Data
public class Bean18 {
	
	private Integer SupplierID;
	private String supplierName;
	private String contactName;
	private String address;
	private String city;
	private String postalCode;
	private String country;
	private String phone;
	
	
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method04
	public int insertSupplier2(Bean18 bean);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method04 -->
	<insert id="insertSupplier2">
		INSERT INTO Suppliers ( SupplierName, ContactName, Address, City, PostalCode, Country, Phone)
		VALUES (#{supplierName}, #{contactName}, #{address}, #{city}, #{postalCode}, #{country}, #{phone} )
	</insert>


</mapper>

○결과값

요청전 Supplers 테이블

http://localhost:8080/controller/cont12/met04 요청시

토르가 추가

 

 

 

 

 

 

 

★Controller12의 method05

insert에 대한 이야기럴 더해보면 

사용자로부터 값을 requestParameter로 받을 값을 bean에 세팅한 이후 insert메소드를 실행할텐데

실행한 이후에 키의값이 얼마인지 알고 싶을때가 있다. 

그러면 마지막에 입력한 키값을 알아내면 되는게 아닌가?  싶지만

 

테이블에는 여러명이 동시에 입력 가능한 테이블이다. 

만약에  여러분들잉 네이버에 회원가입을 하는데 네이터 테이블 목록이라고 하면

user1과 user2가 동시에 회원가입을 하려고했습니다. user1이 키값을 6번, user2가 키값을 7번 받았다고 하면

거의 동시에 이루어져서 insert한 이후 getLastKey 하려고 하는 순간

동시에 이루어져서  user1에서 7번을 가지고 올수 있는 오류가 생길수 있다.

insert하자마자 SELECT 하는 순간이 안전하지 않다고 한다 (동시에 INSERT 요청이 들어올수 있어서)

해결책이 여러가지 있는데 

오라클에서는 번호를 관리하는 sequence라는 쿼리가 따로 있어 INSERT하기전 번호를 채번한다

그 번호를 가지고 INSERT 하게 된다.

getNextSequence and insert , getNextSequence and insert 이런 방식으로 오라클에서는 한다.

 

현재 mariadb는 insert했을 때 자동 인크리먼트되는 키를 가지고 있다

인서트하자마 바로 알아낼 수 있는 방법이 JDBC에있는데 어려워서 생략하고

mybatis에서는 아래와 같은 방법을 사용

 

지금 하고 싶은건 bean17을 재사용해서 인서트하자마자 키를 알고 싶다. 마지막 키를 조회하는건 위험해서. 바로 알아야함

 

xml 에서 옵션이 들어간다.

<insert> 태그 안에

useGeneratedKeys="true" keyProperty="id" keyColumn="customerID"

 

useGeneratedKeys : 자동생성된 키를 사용할 것인가?  기본값은 false

자동생성된 키값을 어느 프로퍼티에 넣을 것인가에서 bean17에 set머머머 메소드가 있다. 

그게 id이다

keyColumn="customerID" 는 테이블에 있는 key column명 이고

keyProperty="id" bean이 가지고 있는 프로퍼티 명이다

 

 

 

Controller12 의 method05

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met05")
	public void method05( ) {
		// 2. request 분석, 가공
		Bean17 bean = new Bean17();
		bean.setCustomerName("danvers");
		bean.setContactName("marvel");
		bean.setAddress("seoul");
		bean.setCity("gangnam");
		bean.setPostalCode("9999");
		bean.setCountry("france");
		
		// 3. insert 하기전 id
		System.out.println(bean.getId()); // null or 0
		
		
		mapper.insertCustomer3(bean);
		
		System.out.println(bean.getId()); //인서트 한이후 key
		
	}
	}
	
}

이전에는 CustomerId를 세팅한적이 없다.

System.out.println(bean.getId()); // Primitive 타입이면 0, Integer 타입이면null

 

Bean17

customerId -> id로 변경 차이점 보여주려고 (무시)

package org.zerock.controller.p05controller.bean;

import lombok.Data;

@Data
public class Bean17 {

		private Integer id;
		private String customerName;
		private String contactName;
		private String city;
		private String address;
		private String postalCode;
		private String country;
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method06
	public int insertSupplier3(Bean18 bean);
    
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method05 -->
	<insert id="insertCustomer3" useGeneratedKeys="true" keyProperty="id" keyColumn="customerID">
	INSERT INTO Customers (CustomerName, ContactName, Address, PostalCode, Country, City)
	VALUES (#{customerName}, #{contactName}, #{address}, #{postalCode}, #{country}, #{city} )

	</insert>


</mapper>

○결과값

요청전 Customers 테이블 정보

 

http://localhost:8080/controller/cont12/met05 요청시

 

값들 참고

 

 

 

 

★Controller12의 method06

 

method06

useGeneratedKeys="true"  // 기본값은 false임
keyProperty="supplierID" 
keyColumn="SupplierID"

useGeneratedKeys : (insert, update에만 적용) 자동생성 키를 받을때 true로 설정한다. (default: false)
keyProperty : 리턴 될 key property 설정. 여러개를 사용한다면 ,(콤마)를 구분자로 나열한다.

 

 

Controller12 의 method06

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
    
	@RequestMapping("/met06")
	public void method06() {
		// 2.
		Bean18 bean = new Bean18();
		bean.setSupplierName("wade");
		bean.setContactName("deadpool");
		bean.setAddress("yeoksam");
		bean.setCity("seoul");
		bean.setPostalCode("3333");
		bean.setCountry("UK");
		bean.setPhone("111");
		
		// 3. mapper 실행
		System.out.println(bean.getSupplierID());  // null or 0
		
		mapper.insertSupplier3(bean);
		
		System.out.println(bean.getSupplierID());  // key
	}

	
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method06
	public int insertSupplier3(Bean18 bean);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method06 -->
	<insert id="insertSupplier3" useGeneratedKeys="true" keyProperty="supplierID" keyColumn="SupplierID">
	INSERT INTO Suppliers (SupplierName, ContactName, Address, City, PostalCode, Country, Phone)
	VALUE (#{supplierName}, #{contactName}, #{address}, #{city}, #{postalCode}, #{country}, #{phone} )
	
	</insert>

</mapper>

 

○결과값

요청하기전 Suppliers 테이블 정보

 

http://localhost:8080/controller/cont12/met06 요청시

 

 

 

 

★Controller12의 method07

 

xml에서

<update id="메소드명">

resultType 이없다 executeQuery쓰기 때문에 몇개의 레코드에 영향을 미쳤는지만 리턴 즉 int타입을 리턴

(insert에서 한것처럼)

쿼리 작성할때 예시

우리는 파라미터로 받은 bean의 프로퍼티를 꺼내서 세팅할 예정이라 insert 할때처럼 ? 가아닌 #{ } 을이용

( #{프로퍼티명})

 

update쿼리연습 할 때 자신의 테이블에 존재하는 것을 업데이트 (기존에있던것을 업데이트해야함)

 

	UPDATE Customers
	SET
		CustomerName =?,
		ContactName =?,
		Address= ?,
		City = ?,
		PostalCode = ?,
		Country = ?,
		Phone = ?
	WHERE
		CuStomerID = ?	


	UPDATE Customers
	SET
		CustomerName = #{customerName},
		ContactName = #{contactName},
		Address= #{address},
		City = #{city},
		PostalCode = #{postalCode},
		Country = #{country},
	WHERE
		CuStomerID = #{id}

 

 

 

Controller12 의 method07

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
    	@RequestMapping("/met07")
	public void method07() {
		// 2
		Bean17 bean = new Bean17();
		bean.setId(111);
		bean.setCustomerName("widow");
		bean.setContactName("nat");
		bean.setAddress("jongro");
		bean.setCity("Asgard");
		bean.setCountry("korea");
		bean.setPostalCode("77777");
		// 3
		int cnt = mapper.updateCustomer(bean);
		System.out.println(cnt);
	}

	
}

 

Bean17

package org.zerock.controller.p05controller.bean;

import lombok.Data;

@Data
public class Bean17 {

		private Integer id;
		private String customerName;
		private String contactName;
		private String city;
		private String address;
		private String postalCode;
		private String country;
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method07
	public int updateCustomer(Bean17 bean);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method07 -->
	<update id="updateCustomer">
	UPDATE Customers
	SET
		CustomerName = #{customerName},
		ContactName = #{contactName},
		Address= #{address},
		City = #{city},
		PostalCode = #{postalCode},
		Country = #{country}
	WHERE
		CuStomerID = #{id}	
	</update>

</mapper>

○결과값

요청전 Customers 테이블

 

 

http://localhost:8080/controller/cont12/met07 요청시

CustomerID = 111인것 스팡이더맨에서 위도우로 바뀜 콘솔창도 1 출력

 

 

 

○결과값

 

 

 

 

★Controller12의 method08

method07 연습 Suppliers 테이블 가지고

 

Controller12 의 method08

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
    	// TODO : update Supplier
	@RequestMapping("/met08")
	public void method08() {
		// 2 request 가공 분석?
		Bean18 bean18 = new Bean18();
		bean18.setSupplierID(45);
		bean18.setSupplierName("Anastasiya");
		bean18.setContactName("NikolaYevna");
		bean18.setAddress("Don");
		bean18.setCity("Rostov");
		bean18.setPostalCode("863");
		bean18.setCountry("russia");
		bean18.setPhone("1119875");
		
		
		// 3.
		int cnt = mapper.updateSupplier(bean18);
		System.out.println(cnt);
		
	}

	
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {
	
    //method08
	public int updateSupplier(Bean18 bean18);

		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->

<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method08 -->
	<update id="updateSupplier">
	UpDATE Suppliers
	SET
		SupplierName = #{supplierName},
		ContactName = #{contactName},
		Address = #{address},
		City = #{city},
		PostalCode = #{postalCode},
		Country = #{country},
		Phone = #{phone}
	WHERE	
		SupplierID = #{SupplierID}
	</update>


</mapper>

○결과값

요청전 Suppliers 테이블정보 

 

 

http://localhost:8080/controller/cont12/met08 요청시

 

 

 

 

---------------------------------------------오후----------------------------------------------------

 

 

1.#{} 자동으로 값에 따옴표가 붙고 성능 좋음

2.${}  그대로 전달 따옴표 안붙음 성능 좋지 않음 보안 취약

3.ORDER BY 아니면 #{} 쓰기.

 

 

 

 

 

 

★Controller12의 method09

 

쿼리내용 삭제하는 DELETE를알아보자

삭제할id의값을 쿼리스트링으로 붙어서

 

삭제쿼리 할때는 검토를 많이 해야함

WHERE빼먹지 않았는지 테이블명은 맞는지, 조건을 잘 썻는지 primary key를 쓰고있는게 맞는지..등등

 

파라미터 에 들어간 id 가 쿼리에 작성한#{id}에 들어감

 

지우는 요청시 자기 테이블 보고 판단 

 

 

Controller12 의 method09

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;
	
	@RequestMapping("/met09")
	public void method09(Integer id) {
		int cnt = mapper.deleteCustomer(id);
		
		System.out.println(cnt);  // cnt  가 1인지 아닌지 에따라 따른 구문으로 처리해줘야함
	}

	
}

 

 

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method09
	public int deleteCustomer(Integer id);
		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!--delete  method09  -->
	<delete id="deleteCustomer">
	DELETE FROM Customers WHERE CustomerID = #{id}
	
	</delete>


</mapper>

○결과값

요청전 정보(94번지워보려고 )

 

http://localhost:8080/controller/cont12/met09?id=94 요청시

 

CustomerID= 94 가 없어짐

 

 

★Controller12의 method10

 

Suppliers 테이블에서 Delete 해보기

 

Controller12 의 method10

package org.zerock.controller.p05controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zerock.mapper.p05mapper.Mapper03;

import lombok.Setter;

@Controller
@RequestMapping("/cont12")
public class Controller12 {

	@Setter(onMethod_ = @Autowired )
	private Mapper03 mapper;

	@RequestMapping("/met10")
	public void method10(Integer id) {
		int cnt = mapper.deleteSuppliers(id);
		
		System.out.println(cnt);  // cnt  가 1인지 아닌지 에따라 따른 구문으로 처리해줘야함
		
	}


	
}

 

Mapper03

package org.zerock.mapper.p05mapper;

import org.apache.ibatis.annotations.Param;

public interface Mapper03 {

	//method10
	public int deleteSuppliers(Integer id);

		
}

 

 

 

Mapper03.xml

<?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">
<!--namespace 속성 : 인터페이스명 -->
<!--id 속성 : 메소드명 -->
<!--resultType 속성 : 컬럼이 매핑될 빈 이름 -->


<mapper namespace="org.zerock.mapper.p05mapper.Mapper03">

	<!-- method010 -->
	<delete id="deleteSuppliers">
	DELETE FROM Suppliers WHERE SupplierID = #{id}
	</delete>



</mapper>

○결과값

요청전 Suppliers 테이블 정보

 

 

http://localhost:8080/controller/cont12/met10?id=47 요청시

SupplierId= 47의 wade deadpool..어쩌구저쩌구 사라짐

 

 

 

 

 

 

 

 

 

 

2021-12-09에서

오후에 어떤 과정을위해 설치하는데 그거는 나중에..