수업(국비지원)/Mybatis
[MYBATIS] Mybatis DB연결하기
byeolsub
2023. 4. 21. 21:02
📌 Main.java 생성
package main;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import mapper.StudentMapper;
public class Main1 {
private static SqlSessionFactory sqlMap;
static { //static 초기화 블럭 : 클래스 변수 초기화 담당
//바이트형 입력 스트림.
InputStream input = null;
try {
//input : mybatis-config.xml의 내용 저장
input = Resources.getResourceAsStream("mapper/mybatis-config.xml");
} catch(IOException e) {
e.printStackTrace();
}
//sqlMap : Mybatis 설정 객체
//mybatis-config.xml 파일을 읽어, 결과들을 sqlMap 변수 저장
//1. db와 연결 완료
//2. sql 구문들을 저장
sqlMap = new SqlSessionFactoryBuilder().build(input);
}
private static Class<StudentMapper> cls = StudentMapper.class;
public static void main(String[] args) {
//session : sqlMap객체에 저장된 db로 접속.
SqlSession session = sqlMap.openSession();
System.out.println("모든 학생 정보 조회하기");
List<Student> list = session.getMapper(cls).select();
for(Student s : list) System.out.println(s);
System.out.println("1학년 학생 정보 조회하기");
list = session.getMapper(cls).select_grade(1);
for(Student s : list) System.out.println(s);
System.out.println("2학년 학생 정보 조회하기");
list = session.getMapper(cls).select_grade(2);
for(Student s : list) System.out.println(s);
System.out.println("학번으로 학생 정보 조회하기");
list = session.getMapper(cls).select_studno("9711");
for(Student s : list) System.out.println(s);
System.out.println("이름에 김자가 들어가는 학생 정보 조회하기");
list = session.getMapper(cls).select_like("김");
for(Student s : list) System.out.println(s);
System.out.println("이름에 김자가 들어가는 학생 정보 조회하기2");
list = session.getMapper(cls).select_like("%김%");
for(Student s : list) System.out.println(s);
}
}
📌 StudentMapper.java -interface로 생성
package mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import main.Student;
public interface StudentMapper {
/*
* db의 컬럼명과 Student의 프로퍼티를 비교하여 같은 이름의 데이터를 저장
*/
@Select("select * from student")
public List<Student> select();
@Select("select * from student where grade = #{value}")
public List<Student> select_grade(int grade);
@Select("select * from student where studno = #{value}")
public List<Student> select_studno(String studno);
@Select("select * from student where name like '%${value}%'")
public List<Student> select_like(String name);
@Select("select * from student where name like #{value}")
public List<Student> select_like2(String name);
/*
* #{value} : 매개변수의 값 + 자료형을 인식함.
* where name =#{value} => where name= '홍길동'
* where name like %#{value}%
* -> where name like %'김'%
* where name like '%#{value}%'
* -> where name like '%'김'%'
* ${value} : 매개변수의 값 => 값만 치환 가능
* where name=${value} => where name = 홍길동
* where name like '%${value}%'
* -> where name like '%김%'
*/
}
📌 Student.java
package main;
import java.util.Date;
public class Student {
private int studno;
private String name;
private String id;
private int grade;
private String jumin;
private Date birthday;
private String tel;
private int height;
private int weight;
private int deptno1;
private int deptno2;
private int profno;
//getter, setter, toString
public int getStudno() {
return studno;
}
public void setStudno(int studno) {
this.studno = studno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getJumin() {
return jumin;
}
public void setJumin(String jumin) {
this.jumin = jumin;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getDeptno1() {
return deptno1;
}
public void setDeptno1(int deptno1) {
this.deptno1 = deptno1;
}
public int getDeptno2() {
return deptno2;
}
public void setDeptno2(int deptno2) {
this.deptno2 = deptno2;
}
public int getProfno() {
return profno;
}
public void setProfno(int profno) {
this.profno = profno;
}
@Override
public String toString() {
return "Student [studno=" + studno + ", name=" + name + ", id=" + id + ", grade=" + grade + ", jumin=" + jumin
+ ", birthday=" + birthday + ", tel=" + tel + ", height=" + height + ", weight=" + weight + ", deptno1="
+ deptno1 + ", deptno2=" + deptno2 + ", profno=" + profno + "]";
}
}