JAVAWEB学习文章索引点这里
注意事项:
1,程序结构为BaseDao,PersonDao和StudentDao直接继承BaseDao。BaseDao中写一些通用点的方法
2,需要导入dbutils,c3p0,mysql驱动等包
3,表分别为person(id,name),student(id,name)预先填入了部分数据
首先介绍用于获取数据源的DBUtils:
package com.dbutils;
import java.beans.PropertyVetoException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtils {
public static ComboPooledDataSource ds = new ComboPooledDataSource();
static {
try {
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
ds.setUser("root");
ds.setPassword("123456");
ds.setInitialPoolSize(5);//设置初始化连接数量
ds.setMaxPoolSize(10);//设置最大连接数量
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static DataSource getDataSource() {
return ds;
}
}
PersonDao:
package com.dao;
import com.bean.Person;
public class PersonDao extends BaseDao<Person>{
}
StudentDao:
package com.dao;
import com.bean.Student;
public class StudentDao extends BaseDao<Student>{
}
BaseDao:
package com.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.dbutils.DBUtils;
public class BaseDao<T> {
Class T_class;
public BaseDao() {
/*
* Type 是 Java 编程语言中所有类型的公共高级接口。
* 它们包括原始类型、参数化类型、数组类型、类型变量和基本类型
* */
//假设PersonDao调用,这里得到的是 Type类型的BaseDao<Person>
Type type = this.getClass().getGenericSuperclass();
//将type转成参数化类型,得到的是参数化类型的BaseDao<Person>
ParameterizedType ptype= (ParameterizedType)type;
//获取泛型内容数组
Type[] actTypeArgs = ptype.getActualTypeArguments();
//由于Class类似Type接口的实现类,所以进行一个强转,得到Person类的
T_class = (Class)actTypeArgs[0];
}
public List<T> selectAll() {
try {
String sql = "select * from "+ T_class.getSimpleName().toLowerCase();
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
return (List<T>)qr.query(sql, new BeanListHandler(T_class));
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
最后在service中测试方法:
package com.service;
import java.util.*;
import org.junit.jupiter.api.Test;
import com.bean.*;
import com.dao.PersonDao;
import com.dao.StudentDao;
public class MyService {
public List<Person> getPersonList(){
return new PersonDao().selectAll();
}
public List<Student> getStudentList(){
return new StudentDao().selectAll();
}
@Test
public void test() {
for (Person person : getPersonList()) {
System.out.println(person.toString());
}
for (Student student : getStudentList()) {
System.out.println(student.toString());
}
}
}
运行结果:
Person [id=1, name=令狐冲]
Person [id=2, name=任我行]
Student [id=1, name=张三]
Student [id=2, name=李四]