MyBatis使用,將Class對象的所有信息添加到SQL server並導出爲XML和json

mybatis配置文件 mybatis-config.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
				<property name="url"
					value="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=homework01" />
				<property name="username" value="sa" />
				<property name="password" value="******" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="hhuc/mapper/HW01InfoMapper.xml" />
	</mappers>
</configuration>

mybatis工具類 MybatisUtils.java

package hhuc.mybatis;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * author:cenhelm
 * mybatis工具類
 */

public class MybatisUtils {
	private static final String FILE_CONFIG = "mybatis-config.xml";
	private static SqlSessionFactory sqlSessionFactory ;
	private MybatisUtils() {}
	static {
		InputStream inputStream;
		try {
			//讀取mybatis配置文件
			inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(FILE_CONFIG);
			//創建會話工程(連接工廠)
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 獲取自動提交的會話
	 * @return
	 */
	public static SqlSession getSqlSessionAutoCommit() {
	SqlSession session=sqlSessionFactory.openSession(true);
	return session;
	} 
	
	public static SqlSession getSqlSession() {
		return sqlSessionFactory.openSession();
	}
}

mapper映射文件 HW01InfoMapper.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="hhuc.mapper.HW01InfoMapper">
	<insert id="insertClassInfo"
		parameterType="hhuc.javabean.ClassInfo" useGeneratedKeys="true"
		keyProperty="classId">
		insert into ClassInfo(className)
		values ( #{className} )
	</insert>
	<insert id="insertMethodInfo"
		parameterType="hhuc.javabean.MethodInfo" useGeneratedKeys="true"
		keyProperty="methodId">
		insert into MethodInfo(classId, methodName, returnType)
		values ( #{classId}, #{methodName}, #{returnType} )
	</insert>
	<insert id="insertParamInfo"
		parameterType="hhuc.javabean.ParamInfo" useGeneratedKeys="true"
		keyProperty="paramId">
		insert into ParamInfo(methodId, paramIndex, paramType)
		values ( #{methodId}, #{paramIndex}, #{paramType} )
	</insert>
	
    <select id="findClassId" resultType="long">
       select classId from ClassInfo where className = #{className}
    </select>
	<select id="findMethodId" resultType="long">
	<!-- 這個max()聚集函數是關鍵,因爲我在後面要獲取參數表裏的methodId這個外鍵,而通過methodName會檢索到多個id,也就是相同方法名有多個方法id,而這個id只要取最大的就一定對了 -->
       select max(methodId) from MethodInfo where methodName = #{methodName}
    </select>
    
    <select id="selectClassInfo" resultType="hhuc.javabean.ClassInfo">
    	select * from ClassInfo
    </select>
    <select id="selectMethodInfo" resultType="hhuc.javabean.MethodInfo">
    	select * from MethodInfo
    </select>
    <select id="selectParamInfo" resultType="hhuc.javabean.ParamInfo">
    	select * from ParamInfo
    </select>
    

</mapper>

定義映射接口 HW01InfoMapper.java

package hhuc.mapper;

import org.apache.ibatis.annotations.Mapper;

import hhuc.javabean.ClassInfo;
import hhuc.javabean.MethodInfo;
import hhuc.javabean.ParamInfo;

/*
 * 定義映射接口(mapper爲mybatis執行數據庫操作的接口類)
 */

@Mapper
public interface HW01InfoMapper {
	void insertClassInfo(ClassInfo obj);
	void insertMethodInfo(MethodInfo obj);
	void insertParamInfo(ParamInfo obj);
	long findClassId(String className);
	long findMethodId(String methodName);
	ClassInfo[] selectClassInfo();
	MethodInfo[] selectMethodInfo();
	ParamInfo[] selectParamInfo();
}

ClassInfo表的java對象 ClassInfo.java

package hhuc.javabean;

/*
 * author:cenhelm
 * homework01數據庫裏面的ClassInfo表,javabean規範
 */

public class ClassInfo {
	private String className;
	public ClassInfo() {}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	
}

MethodInfo表的java對象 MethodInfo.java

package hhuc.javabean;

/*
 * author:cenhelm
 * homework01數據庫MethodInfo數據庫,javabean規範
 */

public class MethodInfo {
	private String methodName;
	private String returnType;
	private long classId;
	public MethodInfo() {}
	public String getMethodName() {
		return methodName;
	}
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}
	public String getReturnType() {
		return returnType;
	}
	public void setReturnType(String returnType) {
		this.returnType = returnType;
	}
	public long getClassId() {
		return classId;
	}
	public void setClassId(long classId) {
		this.classId = classId;
	}
	
}

ParamInfo表的java對象 ParamInfo.java

package hhuc.javabean;

/*
 * author:cenhelm
 * homework01數據庫paramInfo表,javabean規範
 */

public class ParamInfo {
	private int paramIndex;
	private String paramType;
	private long methodId;
	public ParamInfo() {}
	public int getParamIndex() {
		return paramIndex;
	}
	public void setParamIndex(int paramIndex) {
		this.paramIndex = paramIndex;
	}
	public String getParamType() {
		return paramType;
	}
	public void setParamType(String paramType) {
		this.paramType = paramType;
	}
	public long getMethodId() {
		return methodId;
	}
	public void setMethodId(long methodId) {
		this.methodId = methodId;
	}
	
}

XML工具類 XMLUtils.java

package hhuc.xmlTransform;

/*
 * author:cenhelm
 * xml工具類,轉化Java對象到xml輸出
 */

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XMLUtils {
	private static XStream xStream = null;
	// 禁止實例化
	private XMLUtils() {}
	// 利用靜態語句塊初始化Xstream對象
	static {
		xStream = new XStream(new DomDriver("utf-8"));
	}
	//Object-->xml
	public static void saveToFile(String filePath, Object[] objs) {
		try {
			OutputStream os = new FileOutputStream(filePath);
			ObjectOutputStream out = xStream.createObjectOutputStream(os);
			for(Object obj : objs)
				out.writeObject(obj);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

json工具類 JsonUtils.java

package hhuc.jsonTransform;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/*
 * author:cenhelm
 * json工具類,轉化Java對象到json
 */

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonUtils {
	private static Gson gson = null;
	private JsonUtils() {}
	static {
		GsonBuilder builder = new GsonBuilder();
		gson = builder.create();
	}
	
	//obj-->json字符串
	public static void saveToFile(String filePath, Object[] objs) {	
		try {
			OutputStream os = new FileOutputStream(filePath);
			for(Object obj : objs) {
				String str = gson.toJson(obj, obj.getClass());	
				os.write(str.getBytes());
			}
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

測試類

package hhuc.test;

import java.lang.reflect.Method;
import java.util.Scanner;

import org.apache.ibatis.session.SqlSession;

import hhuc.javabean.ClassInfo;
import hhuc.javabean.MethodInfo;
import hhuc.javabean.ParamInfo;
import hhuc.jsonTransform.JsonUtils;
import hhuc.mapper.HW01InfoMapper;
import hhuc.mybatis.MybatisUtils;
import hhuc.xmlTransform.XMLUtils;

public class Test {

	// 插入ClassInfo
	public void insertClassInfo(String className) {
		// 1-獲取會話(連接)
		SqlSession session = MybatisUtils.getSqlSession();
		// 2-獲得映射器對象
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		// 3-創建圖書對象,調用insert方法
		ClassInfo obj = new ClassInfo();
		obj.setClassName(className);
		mapper.insertClassInfo(obj);
		System.out.println("類" + obj.getClassName());
		// 4-提交數據修改
		session.commit();
		// 5-關閉會話
		session.close();
	}

	// 找到classId
	public long findClassId(String className) {
		// 1-獲得一個會話
		SqlSession session = MybatisUtils.getSqlSession();
		// 2-獲得映射器對象
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		// 3-調用查詢方法
		long id = mapper.findClassId(className);
		// 4-關閉會話
		session.close();
		return id;

	}

	// 插入MethodInfo
	public void insertMethodInfo(long classId, String methodName, String returnType) {
		// 1-獲取會話(連接)
		SqlSession session = MybatisUtils.getSqlSession();
		// 2-獲得映射器對象
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		// 3-創建圖書對象,調用insert方法
		MethodInfo obj = new MethodInfo();
		obj.setClassId(classId);
		obj.setMethodName(methodName);
		obj.setReturnType(returnType);
		mapper.insertMethodInfo(obj);
		System.out.println("方法" + obj.getClassId() + " " + obj.getMethodName() + " " + obj.getReturnType());
		// 4-提交數據修改
		session.commit();
		// 5-關閉會話
		session.close();
	}

	// 找到methodId
	public long findMethodId(String methodName) {
		// 1-獲得一個會話
		SqlSession session = MybatisUtils.getSqlSession();
		// 2-獲得映射器對象
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		// 3-調用查詢方法
		long id = mapper.findMethodId(methodName);
		// 4-關閉會話
		session.close();
		return id;

	}

	// 插入ParamInfo
	public void insertParamInfo(long methodId, int paramIndex, String paramType) {
		// 1-獲取會話(連接)
		SqlSession session = MybatisUtils.getSqlSession();
		// 2-獲得映射器對象
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		// 3-創建圖書對象,調用insert方法
		ParamInfo obj = new ParamInfo();
		obj.setMethodId(methodId);
		obj.setParamIndex(paramIndex);
		obj.setParamType(paramType);
		mapper.insertParamInfo(obj);
		System.out.println("參數" + obj.getMethodId() + " " + obj.getParamIndex() + " " + obj.getParamType());
		// 4-提交數據修改
		session.commit();
		// 5-關閉會話
		session.close();
	}

	// 查詢ClassInfo表中所有數據
	public ClassInfo[] selectClassInfo() {
		SqlSession session = MybatisUtils.getSqlSession();
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		ClassInfo[] objs = mapper.selectClassInfo();
		return objs;
	}

	// 查詢MethodInfo所有數據
	public MethodInfo[] selectMethodInfo() {
		SqlSession session = MybatisUtils.getSqlSession();
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		MethodInfo[] objs = mapper.selectMethodInfo();
		return objs;
	}

	// 查詢ParamInfo中所有數據
	public ParamInfo[] selectParamInfo() {
		SqlSession session = MybatisUtils.getSqlSession();
		HW01InfoMapper mapper = session.getMapper(HW01InfoMapper.class);
		ParamInfo[] objs = mapper.selectParamInfo();
		return objs;
	}

	// obj-->xml
	public void saveToXml(String filePath, Object[] infos) {
		XMLUtils.saveToFile(filePath, infos);
	}
	
	//obj-->json
	public void saveToJson(String filePath, Object[] infos) {
		JsonUtils.saveToFile(filePath, infos);
	}
	

	public static void main(String[] args) throws Exception {
		System.out.println("輸入完整類名");
		Scanner scanner = new Scanner(System.in);
		String className = scanner.nextLine();
		scanner.close();
		Class cls = Class.forName(className);
		System.out.println("裝載成功");
		System.out.println(cls);

		Test test = new Test();

		// 插入類名信息
		test.insertClassInfo(cls.getName());

		java.lang.reflect.Method[] methods = cls.getDeclaredMethods();
		for (Method method : methods) {
			// 插入方法信息
			test.insertMethodInfo(test.findClassId(cls.getName()), method.getName(), method.getReturnType().getName());

			Class[] paramTypes = method.getParameterTypes();

			for (int i = 1; i <= paramTypes.length; i++) {
				// 插入方法參數信息
				test.insertParamInfo(test.findMethodId(method.getName()), i, paramTypes[i - 1].getName());
			}

		}

		// 存入xml和js
		ClassInfo[] classInfos = test.selectClassInfo();
		test.saveToXml("ClassInfos.xml", classInfos);
		test.saveToJson("ClassInfos.js", classInfos);

		MethodInfo[] methodInfos = test.selectMethodInfo();
		test.saveToXml("MethodInfos.xml", methodInfos);
		test.saveToJson("MethodInfos.js", methodInfos);
		
		ParamInfo[] paramInfos = test.selectParamInfo();
		test.saveToXml("ParamInfos.xml", paramInfos);
		test.saveToJson("ParamInfos.js", paramInfos);
		
		
		
	}

}

https://github.com/Adam-hohai/Java_homework

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章