etConnection(){
Connection conn =null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/business", "root", "123");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public void releaseConnection(ResultSet rs,Statement stat,Connection conn){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这里我的数据库名是business,用户名,密码分别是root和123,大家根据自己的情况自行修改,并且不要忘了引入mysql的jdbc。
最后我们建立一个test类测试一下是否成功。
package com.zzb;
import java.util.Date;
import java.util.List;
import org.junit.Test;
public class TestDB {
BaseDAO dao = new BaseDAO();
@Test
public void testcreate() throws Exception{
StandardSQL standardSQL = new StandardSQL();
String sql = standardSQL.create(new User());
System.out.println(sql);
dao.executeUpdate(sql);
}
@Test
public void testadd() throws Exception{
User user = new User();
user.setName("xiaohong");
user.setValue((float)45.60);
user.setDate(new Date());
dao.add(user);
}
@Test
public void testupdate() throws Exception{
User user = new User();
user.setId(1);
user.setName("xiaowang");
user.setValue((float)90.88);
user.setDate(new Date());
dao.update(user);
}
@Test
public void testquery() throws Exception{
User user = new User();
user.setName("xiaowang");
List
list = dao.query(user);
for(User u: list){
System.out.print(u.getId()+" ");
System.out.print(u.getName()+" ");
System.out.println(u.getDate());
}
}
@Test
public void testdel() throws Exception{
User user = new User();
user.setId(1);
dao.delete(user);
}
}
test类有5个方法,分别测试建表、插入、修改、查询、删除五个操作。
写到这里,我们已经看出,所谓的OR映射就是通过java的对象,使用反射得到对象的信息,然后产生SQL语句,再使用JDBC对数据库进行操作。在这个程序当中,我们没有做事务处理,没有使用连接池,没有做多表的映射,可移植性也做的不好,只是将一个简单的java对象持久化到数据库相应的表中,但作为一个练习,已经阐明了如何去实现自己的OR框架,希望各位看官读完以后能有所启发。写的不好,权当是抛砖引玉,欢迎各看官指点。