通过数据库的分组函数,我们可以很轻易的对数据进行分组。如果要在Java内对查到的分组数据进行处理(不对数据库发出多次查询)。那就可以使用Map对象来处理。将分组关键字段的值作为索引key,entry为一个List或Stringbuffer对象。将内容不断累加到相应的List或Stringbuffer中。最后遍历Map对象取出List或Stringbuffer的内容即可。
XmlGenarator.java
public class XmlGenerator{
@SuppressWarnings("rawtypes")
public static void main(String[] argc){
String resource = "META-INF/conf/mybatis-config.xml";
String root = "D:/xml/";
InputStream inputStream;
String A="",B="",C="",D="";
HashMap<String,StringBuffer> dataMap = new HashMap<String, StringBuffer>();
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
List lists = session.selectList("com.example.service.getData");
for(Object o:lists){
Map map = (Map) o;
A =(String)map.get("A");
B =(String)map.get("B");
C =(String)map.get("C");
D =(String)map.get("D");
String bufferIndex =A+"_"+B;
if(dataMap.containsKey(bufferIndex)){
dataMap.get(bufferIndex).append("<option><dm>"+C+"</dm><mc>"+D+"</mc><pc>"+A+"</pc></option>");
}else{
StringBuffer buffer = new StringBuffer();
buffer.append("<option><dm>"+C+"</dm><mc>"+D+"</mc><pc>"+A+"</pc></option>");
dataMap.put(bufferIndex, buffer);
}
}
Set<String> keySet = dataMap.keySet();
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String index = it.next();
//处理语句
Helper.saveFile(null, root+index+".xml", "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root><select>"+dataMap.get(index).toString()+"</select></root>");
}
session.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Helper.java
public class Helper {
public static void saveFile(String savePalce,String fileName,String context) throws IOException{
if(savePalce!=null){
File dir = new File(savePalce);
if(!dir.exists()){dir.mkdirs();}
}
if(fileName!=null){
String[] parts = fileName.split("/");
int partslen = parts.length,i;
StringBuffer dirName = new StringBuffer();
for(i=0;i<partslen-1;i++){
dirName.append(parts[i]+"/");
}
File dir = new File(dirName.toString());
if(!dir.exists()) {dir.mkdirs();}
File file = new File(fileName);
if(!file.exists()) {file.createNewFile();}
FileOutputStream out=new FileOutputStream(file,false);
if(context!=null){
out.write(context.getBytes("utf-8"));
}
out.close();
}
}
}