大家好
已经过了将近一个星期没有发博客了,手心也有点痒痒的。今天周五一点时间我们看如何编写Dao方法。
这个方法我们是基于SpringMVC框架的,其实出发点是这样的。因为我们很多类的类字段都是不一样的,所以在数据库查找的时候如果每一个类都写一些对应的find方法,那样会不会感觉有点复杂。重要的我们还是要进行代码的复用。假设我们已经搭建好了SpringMVC的框架,而且jdbc也配置好了,,我们的domain类也创建好了,有person类,也有animal类
Class Animal{
private String name;
private String species;
private String area;
}
Animal类
Class Person{
private String name;
private String age;
private int sex;
}
当然我们们在数据库中也创建好了对应的字段,要保证我们创建类的时候属性和数据库中的字段名称是对应的。我们想做一个功能List<Person> findList(){
//do something
}
List<Animal> findList(){
//do something
}
这个两个函数里面的所执行的操作是不是类似的,肯定的,所以我们想做的事情do something里面是有很多代码是可以级进行复用的这个使用我们就有必要创建一个Dao类,
package com.wdg.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wdg.domain.ArticleComment;
import freemarker.template.utility.StringUtil;
public class CommonDao extends JdbcDaoSupport{
private static CommonDao instance;
public CommonDao() {
super();
}
public static CommonDao getInstance(){
if(instance==null){
@SuppressWarnings("resource")
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
instance= (CommonDao)factory.getBean("commonDao");
}
return instance;
}
public int queryInt(String sql){
int count = 0;
count=super.getJdbcTemplate().queryForObject(sql, Integer.class);
return count;
}
public void getUserName(){
String sql="select * from userinfo";
List<Map> result = super.getJdbcTemplate().query(sql, new RowMapper<Map>() {
@Override
public Map<String,String> mapRow(ResultSet rs, int rowNum) throws SQLException {
Map<String,String> row = new HashMap<String, String>();
row.put("rowguid", rs.getString("rowguid"));
return row;
}});
System.out.println(result.toString());
}
public <T> int insert(T record) {
String classpath=record.getClass().toString();
String tablename=classpath.substring(classpath.lastIndexOf('.')+1,classpath.length());
StringBuffer sb=new StringBuffer();
StringBuffer sb1=new StringBuffer();
sb.append("insert into "+tablename+"(");
Field [] fields=record.getClass().getDeclaredFields();
for(Field f:fields){
sb.append(f.getName());
sb.append(",");
String methodname=f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
try {
Method method=record.getClass().getMethod("get"+methodname,null);
Object value=method.invoke(record,null);
if(value==null){
sb1.append(value);
}
else
{
if(value.getClass().toString().indexOf("util.Date")>0)
{
Date d=(Date) value;
java.sql.Date sdate = new java.sql.Date(d.getTime());
value=sdate;
}
sb1.append("\'"+value+"\'");
}
sb1.append(",");
} catch (Exception e) {
e.printStackTrace();
}
}
String sql=sb.toString().substring(0,sb.toString().lastIndexOf(','));
sql=sql+") values("+sb1.toString().substring(0,sb1.toString().lastIndexOf(','))+")";
super.getJdbcTemplate().execute(sql);
return 0;
}
@SuppressWarnings("unchecked")
public <T> List<T> findList(String sql, Class clazz) {
Field [] fields=clazz.getDeclaredFields();
List<Object> list=new ArrayList<Object>();
List<Map<String,Object>> list1=super.getJdbcTemplate().queryForList(sql);
try {
for(int i=0;i<list1.size();i++){
Class classType = Class.forName(clazz.getName());
Object obj = classType.newInstance();
for(Field f:fields){
String methodname=f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
Method method = classType.getMethod("set"+methodname,f.getType());
method.invoke(obj,list1.get(i).get(methodname));
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return (List<T>) list;
}
}
所以我们想获取到实体的list集合的时候,仅仅需要做的就是:
List<Person> getPersonList(){
String sql="select * from person";
return CommonDao.getInstance().findList(sql,Person.class);
}
List<Animal> getPersonList(){
String sql="select * from animal";
return CommonDao.getInstance().findList(sql,Animal.class);
}
是不是很开心,很简洁
但是要实现这些功能之前,需要做的事情配置好对应的jdbc,SpringMVC框架
希望对你有所帮助