[꼭대기] DAO 디자인 모델 의 선 [데이터베이스 만능 조회 조작]

DAO 디자인 모드
여기 DAO 도 하나의 기능 으로 재 활용 효 과 를 실현 합 니 다.
검색 인 스 턴 스 보기:
사용자 클래스
package com.dao.bean;

/*
 *       
 * A class to do one thing
 */
public class Animals {
		private int id;
		private String name;
		private int age;
		private int anId;
		
		public Animals(){
			
		}
		
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		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 int getAnId() {
			return anId;
		}
		public void setAnId(int anId) {
			this.anId = anId;
		}
		
}


제2: 데이터베이스 링크 클래스
package com.jdbc.uitl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/*
 *  DAO   
 *  A class to do one thing
 * 
 */
public class JDBCUtil {
		public static Connection open(){
			
			Connection conn = null;
			
			try {				
				//    
				Class.forName("com.mysql.jdbc.Driver");
				//       
				conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/animal","root","123456");  
				
			}catch (Exception e) {
				System.out.println("       !");
			}
			return conn;
		}
		
		//   2       
		public static void closeRes(Connection conn ,PreparedStatement ps){
			try {
				if(ps!=null){
					ps.close();
				}
				if(conn!=null){
					conn.close();
				}
			} catch (Exception e) {
				System.out.println("         !");
			}
		}
		
		//   3       
		public static void closeRes(Connection conn ,PreparedStatement ps,ResultSet rs){
			try {
				if(rs!=null){
					rs.close();
				}
				if(ps!=null){
					ps.close();
				}
				if(conn!=null){
					conn.close();
				}
			} catch (Exception e) {
				System.out.println("         !");
			}
		}
}

세 번 째:
package com.dao.data;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.jdbc.uitl.JDBCUtil;

/*
 *   DAO
 * 
 * */
public class DaoSelect {
	
	//1、      [      、ArrayList]
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ArrayList getList(Class<?> cl){
		
		ArrayList ar = new ArrayList();	
		
		Connection conn = JDBCUtil.open();
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		//      、      [  .getSimpleName()]
		String sql = "select *  from "+ cl.getSimpleName();
		//    [  .getDeclaredFields()]
		Field[] fi = cl.getDeclaredFields();
		
		try {
			//     
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			Object ob = null;
			
			while(rs.next()){
		
				ob = cl.newInstance();
				
				for(Field ff : fi){
					//    
					ff.setAccessible(true);
					ff.set(ob, rs.getObject(ff.getName()));
				}
				ar.add(ob);
			}
		} catch (Exception e) {
			System.out.println("          !");
		}finally{
			//    
			JDBCUtil.closeRes(conn, ps, rs);
		}
		return ar;
	}
	
	//2、      [      、Object]
	@SuppressWarnings("rawtypes")
	public Object getObById(Class cl,int id){
		
		Object ob = null;
		
		Connection conn = JDBCUtil.open();
		PreparedStatement ps = null;
		ResultSet rs =null;
		
		//    [  .getDeclaredFields()]
		Field[] fi = cl.getDeclaredFields();
		//     [  .getSimpleName()]
		String sql = "select * from "+cl.getSimpleName()+" where "+fi[0].getName()+" = "+id;     
		
		try {
			//     
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			while(rs.next()){
				
				ob = cl.newInstance();
				
				for(Field ff : fi){
					ff.setAccessible(true);
					ff.set(ob,rs.getObject(ff.getName()));
				}
			}
		} catch (Exception e) {
			System.out.println("          !");
		}finally{
			JDBCUtil.closeRes(conn, ps, rs);
		}
		return ob;
	}
	
	//3、      [      、ArrayList]
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ArrayList getListBySome(Class cl ,String name,Object value){
		
		ArrayList ar = new ArrayList();
		Object ob = null;
		
		Connection conn = JDBCUtil.open();
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		//    、   [  .getDeclaredFields()][  .getSimpleName()]
		Field[] fi = cl.getDeclaredFields();
		String sql = "select * from "+cl.getSimpleName()+" where "+name+" = '"+value+"'";
		
		try {
			//     
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			while(rs.next()){
				
				ob = cl.newInstance();
				
				for(Field ff : fi){
					ff.setAccessible(true);
					ff.set(ob, rs.getObject(ff.getName()));
				}
				ar.add(ob);
			}
			
		} catch (Exception e) {
			System.out.println("          !");
		}finally{
			JDBCUtil.closeRes(conn, ps, rs);
		}
		return ar;
	
	}
}

제4: 실현 류
package com.dao.data;

import java.util.ArrayList;
import com.dao.bean.Animals;


/*
 *     Class
 * 
 */
public class TestSelect {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		DaoSelect dao = new DaoSelect();
		
//		//1、Animals 、    
		ArrayList<Animals> ar = dao.getList(Animals.class);
		for (Animals an: ar) {
			System.out.print("  :" + an.getId() + "——  :" + an.getName());
			System.out.println("——  :" + an.getAge() + "——  ID:" + an.getAnId());
		}
		
//		//2、Animals 、      
//		Animals ar1 = (Animals) dao.getObById(Animals.class, 2);
//		System.out.println("id 2    :" + ar1.getName());
		
		//3、Animals 、      
//		ArrayList<Animals> ar1 = dao.getListBySome(Animals.class, "name", "   ");
//		
//		ArrayList<Animals> ar = dao.getListBySome(Animals.class, "age", "21");
//		for (Animals an: ar ) {
//			System.out.println("  :" + an.getId() + "——  :" + an.getName());
//		}
	}

}

제 5: 데이터베이스 SQL 구문
//      

create database animals ;
use  animals;

create table  animals 
(	id int primary key,  
	name varchar(20) ,
	sex char(2), 
	age int ,
	anid int 
);

좋은 웹페이지 즐겨찾기