1. 程式人生 > >JDBC的DAO設計模式

JDBC的DAO設計模式

DAO:Data Access Object,是訪問資料資訊的類,包含了對資料的CRUD(create,read,update,delete),而不包含任何業務相關的資訊,更容易實現功能的模組化,有利於程式碼的維護和升級。

1.update,包括插入,刪除,更新操作

public void update(String sql,Object ... args){
	Connection connection=null;
	PreparedStatement preparedstatement=null;
	ResultSet resultset=null;
	try{
		connection=JDBCTools.getConnection();
		preparedstatement=connection.prepareStatement(sql);
		for(int i=0;i<args.length;i++){
			preparedstatement.setObject(i+1, args[i]);
		}
		preparedstatement.executeUpdate();
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		JDBCTools.release(resultset,preparedstatement, connection);
	}
}

測試方法:

@Test
public void testUpdate() { String sql="INSERT INTO EXAMSTUDENT(FlowId,TYPE,IdCard,ExamCard,StudentName,Location,Grade)" + "VALUES(?,?,?,?,?,?,?)"; dao.update(sql,1,2,"23313","2321","Li","大連",313); }

2.查詢多條記錄,返回對應的查詢物件的集合

public <T> List<T> getForList(Class<T> clazz,String sql,Object ... args){
	List<T> list=new ArrayList<>();
	Connection connection=null;
	PreparedStatement preparedstatement=null;
	ResultSet resultset=null;
	try{
		//1.得到結果集resultset
		connection=JDBCTools.getConnection();
		preparedstatement=connection.prepareStatement(sql);
		for(int i=0;i<args.length;i++){
			preparedstatement.setObject(i+1, args[i]);
		}
		resultset=preparedstatement.executeQuery();
		//2.處理結果集,將得到的ResultSet結果集中的別名和列值存入到Map中,得到Map的List
		List<Map<String,Object>> listMap = handleResultSetToMapList(resultset);
		//3.將Map的List轉為clazz對應的List,其中Map的key即為clazz對應的屬性名,Map的value為clazz對應的屬性值
		list=transferMapListToBeanList(clazz,listMap);
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		JDBCTools.release(resultset,preparedstatement, connection);
	}
	return list;
}

2.1 得到結果集

2.2 將ResultSet結果集轉換為MapList的方法:handleResultSetToMapList(resultset)

private List<Map<String, Object>> handleResultSetToMapList(ResultSet resultset)
		throws Exception, SQLException {
	List<Map<String,Object>> list=new ArrayList<>();
	//得到resultset中的列名
	List<String> columnLabels=getColumnLabels(resultset);
	Map<String,Object> map=null;
	while(resultset.next()){
		map=new HashMap<>();
		//得到SQL查詢的列數
		int count=columnLabels.size();
		for(String columnLabel:columnLabels){
			Object columnValue=resultset.getObject(columnLabel);
			//將別名,列值存入到Map中
			map.put(columnLabel,columnValue);
		}
		list.add(map);
	}
	return list;
}

其中得到resultset中的列名的方法:getColumnLabels(resultset)

private List<String> getColumnLabels(ResultSet resultset) throws Exception{
	List<String> labels=new ArrayList<String>();
	ResultSetMetaData rsmd=resultset.getMetaData();
	int count=rsmd.getColumnCount();
	while(resultset.next()){
		for(int i=0;i<count;i++){
			labels.add(rsmd.getColumnLabel(i+1));
		}
	}
	return labels;
}

2.3 將MapList轉換為javaBean屬性對應的List:transferMapListToBeanList(clazz,listMap)

private <T> List<T> transferMapListToBeanList(Class<T> clazz,List<Map<String, Object>> listMap) throws InstantiationException, IllegalAccessException, InvocationTargetException {
	List<T> result=new ArrayList<>();
	T bean=null;
	if(listMap.size()>0){
		//listMap中存的是多條記錄的列名和列值,遍歷listMap
		for(Map<String,Object> map1:listMap){
			bean=clazz.newInstance();
			//遍歷map1
			for(Map.Entry<String, Object> entry:map1.entrySet()){
				String propertyName=entry.getKey();
				Object propertyValue=entry.getValue();
				BeanUtils.setProperty(bean,propertyName,propertyValue);
			}
			result.add(bean);
		}
	}
	return result;
}

測試方法:

@Test
public void testGetForList() {
	String sql="SELECT FlowID flowId,TYPE type,IDCard idCard,ExamCard examCard,"
			+ "StudentName studentName,Location location,Grade grade FROM EXAMSTUDENT";
	List<Student> student=dao.getForList(Student.class,sql);
	System.out.println(student);
}

3.查詢一條記錄,返回對應的物件

public <T> T get(Class<T> clazz,String sql,Object ... args){
	List<T> result=getForList(clazz,sql,args);
	if(result.size()>0){
		return result.get(0);
	}
	return null;
}

4.返回某條記錄的某一個欄位的值或一個統計的值(一共有多少條記錄等)

public <E> E getForValue(String sql,Object ... args){
	Connection connection=null;
	PreparedStatement preparedstatement=null;
	ResultSet resultset=null;
	try{
		connection=JDBCTools.getConnection();
		preparedstatement=connection.prepareStatement(sql);
		for(int i=0;i<args.length;i++){
			preparedstatement.setObject(i+1, args[i]);
		}
		resultset=preparedstatement.executeQuery(); 
		if(resultset.next()){
			return (E)resultset.getObject(1);
		}
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		JDBCTools.release(resultset,preparedstatement, connection);
	}
	return null;
}

 測試方法:

@Test
public void testGetForValue() {
	String sql="SELECT ExamCard FROM EXAMSTUDENT WHERE FlowId=?";
	String ExamCard=dao.getForValue(sql,1);
	System.out.println(ExamCard);
}