mybatis如何实现注解sql的简单例子
最近马上要开动项目了,后台是用mybatis,开始研究mybatis,发现
public class TestMain {public static void main(String[] args) {try {//代理SqlInterface sqlInterface = (SqlInterface) Proxy.newProxyInstance(SqlInterface.class.getClassLoader(),new Class[] { SqlInterface.class }, new InvocationHandler() {public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {// TODO Auto-generated method stub//获取注解的sql语句String sqlString = null;if (method.getAnnotation(MySelect.class) != null) {sqlString = method.getAnnotation(MySelect.class).value();System.out.println(sqlString);}String databaseDriver = "com.mysql.jdbc.Driver";Connection conn = null;ResultSet rs = null;try {Class.forName(databaseDriver);conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8","root", "root");PreparedStatement stmt = conn.prepareStatement(sqlString);rs = stmt.executeQuery();} catch (Exception e) {e.printStackTrace();}// 获取数据库字段名称ResultSetMetaData rsmd = rs.getMetaData();String[] dataMetas = new String[rsmd.getColumnCount()];int colcount = rsmd.getColumnCount();for (int i = 1; i <= colcount; i++) {//dataMetas没有index为0的,从1开始System.out.println(rsmd.getColumnClassName(i));dataMetas[i-1] = rsmd.getColumnName(i);}// 获取返回值类型,就是userPOObject o = method.getReturnType().newInstance();while (rs.next()) {Field[] fields = o.getClass().getDeclaredFields();for (Field field : fields) {String fieldname = field.getName();for (String dateMeta : dataMetas) {if (fieldname.toLowerCase().equals(dateMeta)) {field.set(o, rs.getObject(dateMeta));break;}}}}try {rs.close();conn.close();} catch (Exception e) {}return o;}});UserPO po = sqlInterface.select();System.out.println(po.getUserName());} catch (Exception e) {e.printStackTrace();}}}
?这里还是有很多问题的,比如查询带参数,如果返回对象是null或者List,如何处理。
由于只是自己写的一个demo,比较烂,特别是命名和结构,大家了解下原理就好了。
注意run的时候需要mysql-connector-java-5.1.25.jar