Java Web:萬能DAO的使用,查詢功能,用反射調(diào)用DAO,含個人理解與注釋【詩書畫唱】
個人對萬能DAO的好處的理解:就是可以少寫代碼。












實例:

create table Userinfo(
id? int primary key auto_increment,
act varchar(100) not null,
?pwd varchar(100) not null);
insert into Userinfo(
act ,
pwd?
) values ("詩書畫唱用戶名1","888"),
("詩書畫唱用戶名2","666"),
("詩書畫唱用戶名3","777");
select * from Userinfo
___
create table Product(
id int primary key auto_increment,
pname varchar(100) not null,
price double);
insert into Product(
pname,
price?
) values ("詩書畫唱商品1",1.1),
("詩書畫唱商品2",1.2),
("詩書畫唱商品3",1.3);
select * from Product
————————
create table Game(
id int primary key auto_increment,
?gname? varchar(100) not null,
?gtype? varchar(100) not null,
gcomp? varchar(100) not null,
?gyear int)
insert into Game(
gname ,
?gtype ,
gcomp,
?gyear
) values ("詩書畫唱游戲名1","詩書畫唱游戲類型名1","詩書畫唱公司名1",2020),
("詩書畫唱游戲名2","詩書畫唱游戲類型名2","詩書畫唱公司名2",2021),
("詩書畫唱游戲名3","詩書畫唱游戲類型名3","詩書畫唱公司名3",2022);
select * from? Game
drop table? Game
————————
create table studentInfo(
sid int primary key auto_increment,
sname varchar(100) not null,
sgender varchar(100)? default '男' not null,
sage int not null,
saddress varchar(100) ,
semail? varchar(100) );
insert into? studentInfo(
sname ,
sgender ,
sage ,
saddress ,
semail?
) values ("詩書畫唱1",'男','19','北京市朝陽區(qū)','SSHC1@163. com'),
("詩書畫唱2",'男','20','北京市朝陽區(qū)','SSHC2@163. com'),
("詩書畫唱3",'男','30','北京市朝陽區(qū)','SSHC3@163. com');
--drop table studentInfo
--select * from studentInfo
——————————————————————



package com.SSHC.bean;
public class Game {
? ? private Integer id;
? ? private String gname;
? ? private String gtype;
? ? private String gcomp;
? ? private Integer gyear;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getGtype() {
return gtype;
}
public void setGtype(String gtype) {
this.gtype = gtype;
}
public String getGcomp() {
return gcomp;
}
public void setGcomp(String gcomp) {
this.gcomp = gcomp;
}
public Integer getGyear() {
return gyear;
}
public void setGyear(Integer gyear) {
this.gyear = gyear;
}
}

package com.SSHC.bean;
public class Product {
? ? private Integer id;
? ? private String pname;
? ? private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}

package com.SSHC.bean;
public class Userinfo {
? ? private Integer id;
? ? private String act;
? ? private String pwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAct() {
return act;
}
public void setAct(String act) {
this.act = act;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}

package com.SSHC.dao;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.SSHC.bean.Game;
import com.SSHC.bean.Product;
import com.SSHC.bean.Userinfo;
import com.SSHC.util.DbUtil;
//萬能Dao
//T不是一個具體的java類,他是一個泛型參數(shù)
public class BaseDao<T> {
? ? public List<Object>selectAll(Class cls) throws Exception{
? ? Connection conn = null;
? ? PreparedStatement pstm = null;
? ? ResultSet rs = null;
? ? List<Object>list = new ArrayList<Object>();
? ?
? ? //通過反射技術獲取表的名字,表的名字剛好和bean的名字一樣
? ? //獲取類的類名
? ? String tableName = cls.getSimpleName();
? ? String sql = "select * from " + tableName;
? ? System.out.println(sql);
? ?
? ? conn = DbUtil.getConn();
? ? pstm = conn.prepareStatement(sql);
? ? rs = pstm.executeQuery();
? ? //獲取bean中的所有屬性名
Field []fs = cls.getDeclaredFields();
? ? while(rs.next()) {
? ? //通過反射創(chuàng)建出cls對象的實例
? ? Object obj = cls.newInstance();
? ? for(int i = 0;i < fs.length;i ++) {
? ? //bean中的屬性名
? ? String fname = fs[i].getName();
? ? //獲取bean中的屬性的類型
? ? Class type = fs[i].getType();
? ? Object o = rs.getObject(fname);
? ? //System.out.println(o);?
? ? //將屬性對應的set方法名拼接出來
? ? //取出屬性名的首字母,將它變成大寫
String methodName = "set" + fname.substring(0,1).toUpperCase()?
? ? + fname.substring(1);
? ? //System.out.println(methodName);
//通過反射調(diào)用set方法:
Method m = cls.getDeclaredMethod(methodName, type);
System.out.println(m);
? ? m.invoke(obj,o);
? ? }
list.add(obj);
? ? }
? ? return list;
? ? }
? ? public Integer add(T t){
? ? System.out.println(t);
? ? return 0;
? ? }
? ? public Integer update(T t){
? ? return 0;
? ? }
? ? public Integer delete(Integer id){
? ? return 0;
? ? }
? ??
? ? public static void main(String[] args) throws Exception {
? ? ProductDao pd = new ProductDao();
//? ? Product p = new Product();
//? ? pd.add(p);
//? ? List<Object>list = pd.selectAll(Product.class);
//? ? for(Object o : list){
//? ? Product p = (Product)o;
//? ? System.out.println(p.getId());
//? ? System.out.println(p.getPname());
//? ? System.out.println(p.getPrice());
//? ? }
? ?
//? ? UserinfoDao ud = new UserinfoDao();
////? ? Userinfo u = new Userinfo();
////? ? ud.add(u);
//? ? List<Object>list = ud.selectAll(Userinfo.class);
//? ? for(Object o : list) {
//? ? Userinfo u = (Userinfo)o;
//? ? System.out.println(u.getId());
//? ? System.out.println(u.getAct());
//? ? System.out.println(u.getPwd());
//? ? }
//?
////? ? System.out.println(DbUtil.getConn());
//? ?
//? ? GameDao gd = new GameDao();
//? ? List<Object>gl = gd.selectAll(Game.class);
//? ? for(Object o : gl) {
//? ? Game g = (Game)o;
//? ? System.out.println(g.getGname());
//? ? System.out.println(g.getGcomp());
//? ? }
}
}



package com.SSHC.dao;
import com.SSHC.bean.Game;
public class GameDao extends BaseDao<Game> {
// public List<Game>select() throws SQLException{
// ? ? Connection conn = null;
// ? ? PreparedStatement pstm = null;
// ? ? ResultSet rs = null;
// ? ? List<Game>list = new ArrayList<Game>();
// String sql = "select * from Gname";
// ? ? conn = DbUtil.getConn();
// ? ? pstm = conn.prepareStatement(sql);
// ? ? rs = pstm.executeQuery();
// ? ? while(rs.next()) {
// ? ? Integer id = rs.getInt("Id");
// ? ? String Gname= rs.getString("Gname");
// ? ? String gtype = rs.getString("gtype");
// ? ? String gcomp=rs.getString("gcomp");
// ? ? Integer? gyear= rs.getInt("gyear");
//Game g = new Game();
// ? ? g.setId(id);
// ? ? g.setGcomp(gcomp);
// ? ? g.setGname(Gname);
// ? ? g.setGtype(gtype);
// ? ? g.setGyear(gyear);
//list.add(g);
// ? ? }
// ? ? return list;
// ? ? }
}


package com.SSHC.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.SSHC.bean.Product;
import com.SSHC.util.DbUtil;
public class ProductDao extends BaseDao<Product> {
//? ? public List<Product>select() throws SQLException{
//? ? Connection conn = null;
//? ? PreparedStatement pstm = null;
//? ? ResultSet rs = null;
//? ? List<Product>list = new ArrayList<Product>();
//String sql = "select * from product";
//? ? conn = DbUtil.getConn();
//? ? pstm = conn.prepareStatement(sql);
//? ? rs = pstm.executeQuery();
//? ? while(rs.next()) {
//? ? Integer id = rs.getInt("id");
//? ? String pname = rs.getString("pname");
//? ? Double price = rs.getDouble("price");
//? ? Product p = new Product();
//? ? p.setId(id);
//? ? p.setPname(pname);
//? ? p.setPrice(price);
//? ? list.add(p);
//? ? }
//? ? return list;
//? ? }
}


package com.SSHC.dao;
import java.util.List;
import com.SSHC.bean.Userinfo;
public class UserinfoDao extends BaseDao<Userinfo> {
}


package com.SSHC.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class DbUtil {
private static String driverName;
private static String url;
private static String userName;
private static String userPwd;
? ? static {
? ? Properties prop = new Properties();
? ? InputStream is = DbUtil.class.getClassLoader()
? ? .getResourceAsStream("db.properties");
? ? try {
prop.load(is);
driverName = prop.getProperty("dn");
url = prop.getProperty("url");
userName = prop.getProperty("un");
userPwd = prop.getProperty("up");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
? ? }
? ? //獲取數(shù)據(jù)庫連接對象的方法
? ? public static Connection getConn(){
? ? Connection conn = null;
? ? try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,userName,userPwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
? ? return conn;
? ? }
? ? //關閉資源的方法
? ? public static void close(ResultSet rs,PreparedStatement pstm
? ? ,Connection conn){
? ? try {
? ? if(rs != null) {
? ? rs.close();
? ? }
? ? if(pstm != null) {
? ? pstm.close();
? ? }
? ? if(conn != null) {
? ? conn.close();
? ? }
? ? } catch(Exception e) {
? ? e.printStackTrace();
? ? }
? ? }
}


package DiaoYong;
import java.util.List;
import com.SSHC.bean.Game;
import com.SSHC.dao.GameDao;
public class DiaoYongGame {
public static void main(String[] args) throws Exception {
GameDao pd = new GameDao();
// Product p = new Product();
// pd.add(p);
List<Object>list = pd . selectAll(Game.class);
for(Object o: list){
Game g = (Game)o;
System. out. println(g.getId()+"\t"+g.getGname()
+"\t"+g.getGtype()+"\t"+g.getGyear()
+"\t"+g.getGcomp());
}
}}


package DiaoYong;
import java.util.List;
import com.SSHC.bean.Product;
import com.SSHC.dao.ProductDao;
public class DiaoYongProduct {
public static void main(String[] args) throws Exception {
ProductDao pd = new ProductDao();
// Product p = new Product();
// pd.add(p);
List<Object>list = pd . selectAll(Product.class);
for(Object o: list){
Product p = (Product)o;
System. out. println(p. getId()+"? "+p. getPname()+"? "+p.getPrice());
}
}}

package DiaoYong;
import java.util.List;
import com.SSHC.bean.Userinfo;
import com.SSHC.dao.UserinfoDao;
public class DiaoYongUserinfo {
public static void main(String[] args) throws Exception {
UserinfoDao u= new UserinfoDao();
List<Object>list = u.selectAll(Userinfo.class);
for(Object o: list){
Userinfo g = (Userinfo)o;
System. out. println(g.getId()+"\t"+g.getAct()
+"\t"+g.getPwd());
}
}
}

dn=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=UTF-8
un=root
up=root


