실습 5일차_SpEL

 

SpEL - Spring Expression Language
Spring Expression Language는 보통 SpEL로 표기하며 구두로는 Spring EL이라고 지칭한다.
SpEL은 보통 객체를 조회하고 조작하는 기능을 제공하여 Unified EL과 유사하지만
Method 호출, 문자열 템플릿 기능 등의 여러가지 추가 기능을 제공하는 표현식 언어이다.
Spring 3.0부터 지원된다.

 

 Spring SpEL 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean isMarried;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return isMarried;
	}
	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ "]";
	}
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{'신길동'}" />
		<property name="age" value="#{20+10}" />
		<property name="married" value="#{10>4}" />
		<property name="weight" value="#{'75.75'}" />
	</bean>
	
</beans>

 

* 출력 화면 

 

 Spring SpEL_ref 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
	}
}

Cat.java

package com.dto;

public class Cat {

	String name;
	int age;
	String sex;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}

}

Person.java

package com.dto;

public class Person {

	String username;
	int age;
	boolean isMarried;
	double weight;
	
	Cat cat;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isMarried() {
		return isMarried;
	}

	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}

	public double getWeight() {
		return weight;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ ", cat=" + cat + "]";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="c1" class="com.dto.Cat">
	  <property name="name" value="나비" />
	  <property name="age" value="2" />
	  <property name="sex" value="암컷" />
	</bean>

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="57.25" />
		<property name="cat" ref="c1" />  <!-- ref 이전 -->		
	</bean>

    <bean id="p2" class="com.dto.Person">
		<property name="username" value="홍길동" />
		<property name="age" value="30" />
		<property name="married" value="true" />
		<property name="weight" value="77.77" />
		<property name="cat"  value="#{c1}"/>  <!-- SpEL -->  		
	</bean>
</beans>

* 출력 화면 

 

 Spring SpEL_property

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{p1.username}" />
		<property name="age" value="#{p1.age+10}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
</beans>

* 출력 화면 

 

 Spring SpEL_method

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p1 = ctx.getBean("p1", Person.class);
		System.out.println(p1);
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
		Person p4 = ctx.getBean("p4", Person.class);
		System.out.println(p4);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
	// 필요에 의해서 추가된 메서드
	public String getName() {
		return "GOKilDong";

	}
	
	public String getName2() {
		//return "GOKilDong";
		return null;
	}
	
	// static 메서드
	public static String getName3() {
		return "Park";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
										  <!-- 일반 메서드 호출 방법 -->
	<bean id="p1" class="com.dto.Person"> <!-- 필요에 의해서 추가된 메서드에도 접근할 수 있다. SpEL로 메서드 호출 가능 -->
		<property name="username" value="#{p1.getName()}" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName().toUpperCase()}" />
		<property name="age" value="#{p1.age}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
	<bean id="p3" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName2()?.toUpperCase()}" /><!-- 에러 방지? -->
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<bean id="p4" class="com.dto.Person"> <!-- static 메서드 호출 방법 -->
		<property name="username" value="#{T(com.dto.Person).getName3()}" /><!-- .java가 아니기에 pakage명까지 넣어줘야 함 -->
		<property name="age" value="#{T(java.lang.Math).random()+1 * 10.0}" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
</beans>

* 출력 화면 

 

 출처

 

SpEL : https://atoz-develop.tistory.com/entry/Spring-SpEL-Spring-Expression-Language

+ 강의 교재

 

실습 4일차_MyBatis_Transaction ★

 

 Spring MyBatis_Transaction ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");	
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));	
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		// transaction 처리	
		try {
			service.tx();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}

	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
	
	// 트랜잭션 실습 메서드
	public void tx() throws Exception;
	
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

	// 트랜잭션 실습 메서드
	@Transactional
	@Override
	public void tx() throws Exception {
		int num = dao.insert(new DeptDTO(96, "IT", "서울"));
		int num2 = dao.delete(1);
	}
}

dept.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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 트랜잭션 처리 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
  <tx:annotation-driven transaction-manager="txManager"/>
  <!-- 트랜잭션 처리 -->
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.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">
<mapper namespace="com.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_MyBatis ★

 

 Spring MyBatis ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");
		
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}
	
	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
	
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

}

dept.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: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">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.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">
<mapper namespace="com.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	    
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_Component_Scan

 

 

 

 Spring Component_Scan

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
	}
}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

// @Component // @Component는 전부 Class Level
@Repository("dao")
public class UserDAO {
	
	public UserDAO() {
		System.out.println("UserDAO 생성자");
	}

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "홍길동", "신길동");
		return list;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.dao.UserDAO;

// POJO Class
// @Component // @Component는 전부 Class Level
@Service("service")
public class UserService {
	
	@Autowired
	UserDAO dao; // property (인스턴스 변수)
	
	public UserService() {
		System.out.println("UserService 생성자");
	}
	
	public List<String> list(){
		return dao.list();
	}
}

user.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: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">

	<!-- @ 어노테이션 활성화 -->
	<!-- <context:annotation-config /> --> <!-- empty tag -->
	
	<!-- 내부적으로 <context:annotation-config /> 기능 포함 -->

	<!-- 마킹된(Component) Bean들의 Pakage Name 지정 -->
	<context:component-scan base-package="com.service, com.dao" /> <!-- empty tag -->
	<!-- <context:component-scan base-package="com.*" /> -->
</beans>
<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

* Component_Scan : 

+ 강의 교재

 

실습 4일차_@Value_resourceBundle

 

 

 

 Spring @Value_resourceBundle

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Cat c = ctx.getBean("cat1", Cat.class);
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

Cat.java

package com.dto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class Cat {
	
	@Value("${cat.name}")
	String name;
	@Value("${cat.age}")
	int age;
	@Value("${cat.sex}")
	String sex;
	
	public Cat() {

	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	
	String username;
	int userage;
	String address;
	
	//@Autowired(required = false)
	//@Qualifier("cat1")
	@Resource(name = "cat2")
	Cat cat; // null
	
	public Person() {
	
	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

test.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: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">

	<context:annotation-config />

	<context:property-placeholder location="classpath:com/config/cat.properties" file-encoding="utf-8"/> 

	<bean id="cat1" class="com.dto.Cat" />
	<!-- 
	<bean id="cat1" class="com.dto.Cat"> < 생성자로 주입   property라는 setter method 이용-->
		<!-- 	<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	 -->

</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

cat.properties

cat.name = 망치 
cat.age = 2
cat.sex = 수컷

 

* 출력 화면 

 

 출처

 

@Value: 

+ 강의 교재

 

실습 4일차_@Resource

 

 

 

 Spring @Resource

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		Cat c = p1.getCat();
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

Cat.java

package com.dto;
import org.springframework.beans.factory.annotation.Autowired;

public class Cat {
	String name;
	int age;
	String sex;
	
	public Cat() {

	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	
	String username;
	int userage;
	String address;
	
	//@Autowired(required = false)
	//@Qualifier("cat1")
	@Resource(name = "cat2")
	Cat cat; // null
	
	public Person() {
	
	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

user.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: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">

	<context:annotation-config />

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<!--  <property name="cat" ref="cat" /> 자동으로 주입  Cat.java @Autowired 코드 확인-->
	</bean>
</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

@Resource : 

+ 강의 교재

 

+ Recent posts