상세 컨텐츠

본문 제목

[Mybatis] Read Operation,

Mybatis

by kwanghyup 2020. 1. 20. 01:36

본문

Read Operation

 

[1]데이터베스 칼럼 추가 

INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )  
VALUES ('Mohammad','It',80,984803322,'Mohammad@gmail.com');

INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )  
VALUES ('shyam','It',75,984800000,'shyam@gmail.com ');

 

[2] toString 메서드 추가 

Student.java

//toString()메서드 추가 
    @Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", branch=" + branch + ", 
        percentage=" + percentage + ", phone=" + phone + ", email=" + email + "]";
	}

 

[3] 매퍼 설정

Student.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 = "Student">	

   <resultMap id = "result" type = "net.school.lesson.Student">
      <result property = "id" column = "ID"/>	    
   </resultMap>
	
   <select id = "getAll" resultMap = "result">
      SELECT * FROM STUDENT; 
   </select>
    
   <select id = "getById" parameterType = "int" resultMap = "result">
      SELECT * FROM STUDENT WHERE ID = #{id};
   </select>
    	
</mapper>

 

[4] 데이터베이스 모든 칼럼 조회 

MybatisRead_ALL.java

pack:net.mybatis.main

public class mybatisRead_ALL { 

   public static void main(String args[]) throws IOException{

      Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);		
      SqlSession session = sqlSessionFactory.openSession();
      
      //select contact all contacts		
      List<Student> students = session.selectList("Student.getAll");
		
		for(Student student : students) {
			System.out.println(student);
		}
		
      System.out.println("Records Read Successfully ");          
      session.commit();   
      session.close();			
   }
} 

실행 후 결과 확인 

 

[5] 특정 칼럼 조회 

mybatisRead_byID.java

pack:net.mybatis.main

public class mybatisRead_byID {
	
	public static void main(String[] args) throws IOException {
		Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		SqlSession session = sqlSessionFactory.openSession(); 
		
		//select a particular student by id 
		Student student = session.selectOne("Student.getById",1);
		System.out.println(student);
		
		session.commit();
		session.close();
	}
}

실행 후 결과 확인 

'Mybatis' 카테고리의 다른 글

[Mybatis] Delete Operation  (0) 2020.01.20
[Mybatis] Update Operation  (0) 2020.01.20
[Mybatis] Configuration XML, Mapper XML, Create Operation  (0) 2020.01.19

관련글 더보기

댓글 영역