ORM这一块一直用第三方框架,都忘记原生jdbc怎么写了,花了几个小时回忆整理一下。
引用jar:mysql-connector-java-5.0.5-bin.jar
创建公用私有变量
public static final String url = "jdbc:mysql://127.0.0.1/oneshop";public static final String name = "com.mysql.jdbc.Driver";public static final String user = "root";public static final String password = "root";public Connection conn = null;private PreparedStatement pst = null;private ResultSet rs;
构造函数实例化打开连接
public DB() throwsClassNotFoundException, SQLException {
Class.forName(name);//指定连接类型
if (conn == null)
conn= DriverManager.getConnection(url, user, password);//获取连接
}
关闭连接
public void close() throwsSQLException {if (conn != null)
conn.close();if (pst != null)
pst.close();if (rs != null)
rs.close();
}
执行sql方法
publicBoolean execute(String sql, String... params) {boolean bool = false;try{
pst=conn.prepareStatement(sql);for (int i = 0; i < params.length; i++) {
pst.setString((i+ 1), params[i]);
}
bool=pst.execute();this.close();
}catch(SQLException e) {
e.printStackTrace();
}returnbool;
}
查询返回一条数据
public Mapget(String sql, String... params)throwsSQLException {
pst=conn.prepareStatement(sql);for (int i = 0; i < params.length; i++) {
pst.setString((i+ 1), params[i]);
}
rs=pst.executeQuery();
Map map = new HashMap();
ResultSetMetaData rsmd=pst.getMetaData();int col =rsmd.getColumnCount();while(rs.next()) {for (int i = 1; i < col; i++) {
map.put(rsmd.getColumnName(i), rs.getObject(i));
}
}this.close();returnmap;
}
查询返回集合
public List>List(String sql, String... params)throwsSQLException {
pst=conn.prepareStatement(sql);for (int i = 0; i < params.length; i++) {
pst.setString((i+ 1), params[i]);
}
rs=pst.executeQuery();
List> rList = new ArrayList>();
Mapmap;
ResultSetMetaData rsmd=pst.getMetaData();int col =rsmd.getColumnCount();while(rs.next()) {
map= new HashMap();for (int i = 1; i < col; i++) {
map.put(rsmd.getColumnName(i), rs.getObject(i));
}
rList.add(map);
}returnrList;
}
我们常用返回的是实体,而不是map,所以使用了JSONArray
不过这个需要引用很多jar
分别是:
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-codec-1.6.jar
commons-io-2.2.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
这么一大堆jar是个什么鬼?现在可是轻量级服务,怎么能有这么多,,本人表示很烦,决定后面有时间写一个,不过这里就算了,以后再说吧(偷个懒....)
单个查询
public T getEntity(String sql, Class t) throwsSQLException {
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
Map map =get(sql);
JSONArray jr=JSONArray.fromObject(map);
@SuppressWarnings("unchecked")
T result=(T) JSONArray.toCollection(jr, t);returnresult;
}
查询返回集合
public List getList(String sql, Class t) throwsSQLException {
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
List> rList =List(sql);
JSONArray jr=JSONArray.fromObject(rList);
@SuppressWarnings("unchecked")
List resultList = (List) JSONArray.toCollection(jr, t);returnresultList;
}
这样写返回实体有2个限制:
1.实体字段名必须与查询返回的字段名一致,否则无法赋值。
2.只能查询当前实体
果然还是只能自己写一个,思路也大概有了:
1.给实体添加注解,通过反射找到实体字段名与数据库对应字段名,从而解决第一个问题。
2.外键关联的字段可以通过查询的时候as 表名.列名 去解析赋值,解决第二个问题。
嗯,就是这样。