笔记之_java整理框架

时间:2023-02-25 18:22:44
This依赖于对象,static依赖于类
字符串的模糊查询:
instr(empName,
?)>0
empName like ‘
%白%
Create view 表名 as 多表连接 视图是临时表
多表连接语句生成,查询工具点开
<T,K>泛型可以用多个
ResultSetMetaData取得列名集合,rst.getMetaData
Reflect反射,Field[]
实例化对象方法:
New student();
Student.
class.newInstance();
Class.forName(“com.wize.studnet”).newInstance();
反射:在程序运行过程中,对类中的方法或变量进行操作
OneFiled.set(,)委托
OneFileld.setAccessible(
true)访问等级变量
getValue取得easyUI的combobox的选中的值
Object…长度可变数组
集合.toArray():集合转换为数组
easyUI的datagrid分页查询时传过来的参数名称
page:当前第几页
rows:每页显示多少条数据
跨域请求filter的dofilter主要内容:
HttpServletResponse resp
=(HttpServletResponse) response;
resp.setHeader(
"Access-Control-Allow-Origin", this.domain);
maven项目步骤:
1新建maven
2配置pom.xml,此时主要配置的是org.apache.maven.plugins
3添加项目运行环境:项目右键propertiesjava build pathadd libserver runtime选择运行的web服务器
4项目右键propertiesproject facets
-选中Java、JavaScript、Dynamic web module
runtimes选中运行环境
5拷贝web.xml到WEB_INF下,并配置文件
6项目右键propertiesDeployment Assemblyaddjava build path entriesmaven dependencies应用
7未添加项目前打开tomcat双击进入配置deploy path设置为webapps
8发布servers视图中右键add and remove运行
maven的Java代码实现:
1由于要连接数据库,所以pom.xml要导入my sql或Oracle的连接数据库包,依赖jstl包,java测试用的junit包,项目运行日志的log4j包,上传文件工具类的commons
-io包,字符串工具类的commons-lang3
2、log4j配置,虚拟路径src/main/resource下新建log4j.properties文件存放配置内容
3、jdbc的配置,虚拟路径src/main/resource下新建jdbc.properties文件存放配置内容,存放driver,url,userid,userpwd的值,由于连接数据库的参数可变性高,方便改动
4.写BaseDao时要读取jdbc.properties,通过new Properties().load()工具类方法读取,通过BaseDao.class.getResourceAsStream("/jdbc.properties")找到,通过Properties对象.getProperty(“driver”)取出参数
maven的前端展示:
1下载easyUI
2webcontent下新建resource文件夹下新建js、css、images、plugins等文件夹,plugins下新建easyui文件夹并将下载好的easyUI压缩包中的除了demo文件夹外的文件夹及js文件拷贝过来,由于jQuery.min.js使用率较高,将它移动到上面的js文件夹中
3webcontent下新建测试文件夹test下新建idndex.jsp,换成html5,
<!DOCTYPE html ><meta charset="UTF-8">不一样而已
4、easyUI文档网站引入需要的插件easyui.css,icon.css,jquery.min.js,
jquery.easyui.min.js并修改路径,刚才复制的压缩包文件
5、body中复制过来添加展示表格什么的,并根据easyUI英文文档修改
6、由于url是字符串,但又不能写死,所以在js文件夹下新建constants.js存放公共变量,将登陆网址到项目文件夹根目录var ServerURL=
"http://localhost:8080/wisezoneService";并引入该文件
7取值,field后写对象转换后的json名,如marjorId
8显示中文字需要引入easyui
-lang-zh_CN.js
9写JavaScript内部代码解决字符串拼接变量问题url,改写上面整行代码,根据文档插入想要的效果属性$(代码)相当于window.onload,$(‘#dg’)相当于document.getElementById(‘dg’);
项目报错:
警告: [SetPropertiesRule]{Server
/Service/Engine/Host/Context} Setting property 'source'
双击Servers:就是双击服务器名,进入servers的配置界面: 选中
"Publish module contexts to separate XML files"选项
当在pom中引入了依赖包,但是在项目中不能用,找到jar包,项目右键build path导入文件jar包即可
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
选择Deployment Assembly,在右边点击Add按钮,在弹出的窗口中选择Java Build Path Entries
React ative开发手机web app环境
项目包的细分:
com.项目名.entity:实体类
com.项目名.dao:数据访问接口层
BaseDao只写一次
CommonDao
<T>只写一次
entity对应的interfacexxxDao
extends CommonDao<xxx>
com.项目名. dao.impl:数据访问实现层
entity对应的classxxxDaoImpl
extends BaseDao implements xxxDao
com.项目名.service:业务逻辑接口层
CommonService
<T>只写一次
entity对应的interfacexxxService
extends CommonService<xxx>
com.项目名.service.impl:业务逻辑实现层
abstract classCommonServiceImpl<T> implements CommonService<T>引用CommonDao 设定set()方法
entity对应的class xxxServiceImpl
extends CommonServiceImpl<xxx> implement xxxService{
引用xxxDao
Public xxxServiceImpol(){
Super.setCommonDao(xxDao对象名);
}
}
com.项目名.filter:编码过滤的类,CrosFilter、EncodingFilter、GetMessyCodeFilter
com.项目名.web:存放公共的servlet类,继承HttpServlet
com.项目名.web.实体类名:存放具体的继承CommonServlet类的servlet
com.项目名.util:工具包
com.项目名.pojo:小的临时的实体类,为servlet服务的
web容器执行顺序:
项目发布tomcatListener 监听器 (请求参数变化,session变化)
Filter(init,desctory,doFilter)过滤器 (chain.doFilter(请求,响应)指行你指定的页面)
Servlet(init,desctory,service(doGet
/doPost))服务
跨域请求:
不同项目间的访问
谷歌默认禁止跨域请求
https:
//developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
分页页面javascript连接json代码:由于url是字符串,但是网页根目录不能写死,而引入
$(function(){
$(
'#dg').datagrid({
url:ServerURL
+'/api/marjor/search.do',
method:
"post",
pagination:
true, /*分页导航*/
singleSelect:
true, /*只允许选择单行*/
rownumbers:
true, /*显示行号*/
pageSize:
5, /*默认每页显示5笔*/
pageList:[
1,2,5,10,20,30,40,50,100]
});
});
url后的是json对象内容,ajax请求网站地址必须是json格式对象,底层servlet代码转换成json对象并答应的原因
其中ServerURL为自定义的变量名,变量值为项目网址前段部分
get提交乱码问题:
1把servlet请求的参数取出来,转换成为ISO
-8859-1,然后再转换成UTF-8
String n
=new String(name.getBytes("ISO-8859-1"), "UTF-8");
2修改 tomcat
/conf/server.xml 中的 <Connector>
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
3自定义filter对get请求的参数进行转码(先以iso
-8895-1进行解码,然后再以utf-8进行编码)
http:
//www.cnblogs.com/binye-typing/p/6281627.html

ctrl
+T显示子类
source folde虚拟包管理,发布项目的时候不存在
静态内不能用this,类名.class指代类本身
Easyui
datagrid 表格插件它请求默认参数是:
page
=当前是第几页
rows
= 每页显示多少笔数据
easyui datagrid常用属性
rownumbers:
true 显示行号
singleSelect:
true 单选 只能选择一行
pagination:
true 显示分页导航条
url:
'datagrid_data1.json', ajax请求网站地址必须是json格式对象
method:
'get/post' 请求方式
返回 javascript对象
json格式规定的
Java对象如何转换成json(javascript的格式)可以使用很多插件(jar包)
{
"total": 28, 总记录数
"rows": [ rows数据行数 List<T>
{ 键 : 值
"productid": "FI-SW-01",
"productname": "Koi",
"unitcost": 10,
"status": "P",
"listprice": 36.5,
"attr1": "Large",
"itemid": "EST-1"
},
{
"productid": "K9-DL-01",
"productname": "Dalmation",
"unitcost": 12,
"status": "P",
"listprice": 18.5,
"attr1": "Spotted Adult Female",
"itemid": "EST-10"
}
]
}
json
-lib 提供2个类
JSONObject (Map集合) 单个对象
--> javascript {}
JSONArray (List集合) 数组对象
-->javascript []
日期格式化可以写一个类,实现接口JsonValueProcessor
千万不要在JSONObject 或者 JSONArray中直接放对象中存在日期类型,或者直接放日期类型,这样是不会被转换的
JSONArray arr
=new JSONArray();
for(int i=1;i<=3;i++){
Student st1
=new Student();
st1.setBirthday(
new Date());
st1.setId(
"111"+i);
arr.add(st1);
}
Listener监听器:
ServletContextListener监听ServletContext。
当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;
当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。
HttpSessionListener监听HttpSession的操作。
当创建一个Session时,激发session Created(HttpSessionEvent se)方法;
当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。
HttpSessionAttributeListener监听HttpSession中的属性的操作。
当在Session增加一个属性时,激发attributeAded(HttpSessionBindingEvent se) 方法;
当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;
当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。
StringUtil字符串工具判断类:
public class StringUtil extends StringUtils{
}
分页工具类:省去了封装的get()和set()方法
public class PageUtil<T> implements Serializable {
private int pageIndex = 1; // 当前第几页
private int pageSize = 5; // 每页5笔数据
private List<T> data; // 当前页存放的数据
private int totalRecrods; // 总记录数
//mysql排除前几笔(位移笔数) */
public int getOffset(){
return (this.pageIndex-1)*this.pageSize;
}
//mysql取几笔
public int getLimit(){
return this.pageSize;
}
}
日志文件配置:在虚拟路径src
/main/resources下新建log4j.properties文件
log4j.rootLogger
=WARN, stdout, R
log4j.appender.stdout
=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout
=org.apache.log4j.PatternLayout
# Pattern to output the caller
's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO
8601 format
log4j.appender.stdout.layout.ConversionPattern
=%d [%t] %-5p %c - %m%n
log4j.appender.R
=org.apache.log4j.RollingFileAppender
log4j.appender.R.File
=example.log
log4j.appender.R.MaxFileSize
=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex
=1
log4j.appender.R.layout
=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern
=%p %t %c - %m%n
# Print only messages of level WARN or above in the
package com.foo.
log4j.logger.com.foo
=WARN
BaseDao改变:
在虚拟路径src
/main/resources下新建jdbc.properties文件
jdbc.driver
=com.mysql.jdbc.Driver
jdbc.url
=jdbc:mysql://192.168.16.171:3306/wisezone
jdbc.username=root
jdbc.password
=root
BaseDao内容
public class BaseDao {
private static String DRIVER = "";
private static String URL = "";
private static String USERNAME = "";
private static String PASSWORD = "";
protected Connection conn;
protected PreparedStatement prep;
protected ResultSet rst;
static {
// 加载 jdbc.properties 文件 中的信息
Properties prop = new Properties();
try {
prop.load(BaseDao.
class.getResourceAsStream("/jdbc.properties"));

DRIVER
= prop.getProperty("jdbc.driver");
URL
= prop.getProperty("jdbc.url");
USERNAME
= prop.getProperty("jdbc.username");
PASSWORD
= prop.getProperty("jdbc.password");

}
catch (IOException e1) {
e1.printStackTrace();
}
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 打开数据库
protected Connection open_db() throws SQLException {
this.conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return this.conn;
// 关闭连接
protected void close_db() throws SQLException{
if(this.rst!=null){
this.rst.close();
}
if(this.prep!=null){
this.prep.close();
}
if(this.conn!=null){
this.conn.close();
}
}
Json日期格式转换类:
public class JsonDateValueProcessor implements JsonValueProcessor {
private String format ="yyyy-MM-dd";
public JsonDateValueProcessor() {
}
public JsonDateValueProcessor(String format) {
this.format = format;
}
@Override
public Object processArrayValue(Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
@Override
public Object processObjectValue(String paramString, Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
private Object process(Object value){
if(value instanceof Date){
SimpleDateFormat sdf
= new SimpleDateFormat(format,Locale.CHINA);
return sdf.format(value);
}
return value == null ? "" : value.toString();
}
}
web.xml配置文件的引入:
<!-- 跨域访问设定在第一位 -->
<filter>
<filter-name>CrosFliter</filter-name>
<filter-class>com.wisezone.filter.CROSFilter</filter-class>
<init-param>
<param-name>domain</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CrosFliter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- -编码过滤类配置 放在第二位 -->
<filter>
<filter-name>EncodingFliter</filter-name>
<filter-class>com.wisezone.filter.EncodingFiler</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFliter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- -get提交乱码问题解决 -->
<filter>
<filter-name>ISO885901ToUTF8Filter</filter-name>
<filter-class>com.wisezone.filter.ISO885901ToUTF8Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>ISO885901ToUTF8Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Pom.xml配置文件的引入:
<!--
https://mvnrepository.com/artifact/com.oracle/classes12 -->
<dependencies>
<!--------Mysqle数据库导入的包----->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--------Oracle数据库导入的包,一般没有要复制文件----->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>classes12</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/net.sf.json-lib/json-lib 把java对象转换成 json -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier><!--指定jdk版本-->
</dependency>
</dependencies>
<!--
https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
或者
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 测试 junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 使用log4j记录服务器日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<!-- 文件 上传工具类, 字符串相关工具类 -->
<!--
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!--
https://mvnrepository.com/artifact/commons-io/commons-io 文件上传工具包 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!---------httpcient联网jar包--------- -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>



AutoBaseDao类:
public class AutoBaseDao<T> {
private static String DRIVER = "";
private static String URL = "";
private static String USERNAME = "";
private static String PASSWORD = "";
protected Connection conn;
protected PreparedStatement prep;
protected ResultSet rst;
static {
// 加载 jdbc.properties 文件 中的信息
Properties prop = new Properties();
try {
prop.load(AutoBaseDao.class.getResourceAsStream("/jdbc.properties"));
DRIVER = prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int result = 0; // 增,删除,改结果
private Class<T> persistentClass;
@SuppressWarnings("unchecked")
public AutoBaseDao() {
// AutoBaseDao<T> 得到<T>泛型的实际类型
ParameterizedType type = (ParameterizedType) getClass()
.getGenericSuperclass();
persistentClass = (Class<T>) type.getActualTypeArguments()[0];
}
/**
* 过滤当前Pojo类所有带传入字符串的Method对象,返回List集合.
*/
private List<Method> matchPojoMethods(T entity, String methodName) {
// 获得当前Pojo所有方法对象
Method[] methods = entity.getClass().getDeclaredMethods();
// List容器存放所有带get字符串的Method对象
List<Method> list = new ArrayList<Method>();
// 过滤当前Pojo类所有带get字符串的Method对象,存入List容器
for (int index = 0; index < methods.length; index++) {
if (methods[index].getName().indexOf(methodName) != -1) {
list.add(methods[index]);
}
}
return list;
}
/**
* 参数类型为String时,为entity字段设置参数,对应set
*/
public String setString(Method method, T entity, String arg)
throws Exception {
return (String) method.invoke(entity, new Object[] { arg });
}

/**
* 参数类型为Date时,为entity字段设置参数,对应set
*/
public Date setDate(Method method, T entity, Date arg) throws Exception {
return (Date) method.invoke(entity, new Object[] { arg });
}

/**
* 参数类型为Integer或int时,为entity字段设置参数,对应set
*/
public Integer setInt(Method method, T entity, Integer arg)
throws Exception {
return (Integer) method.invoke(entity, new Object[] { arg });
}
/**
* 参数类型为Double或double时,为entity字段设置参数,对应set
*/
public Double setDouble(Method method, T entity, Integer arg)
throws Exception {
return (Double) method.invoke(entity, new Object[] { arg });
}
/**
* 保存
*
*
@param entity
*
@return
*/
public int save(T entity) throws Exception {
String sql
= "INSERT INTO "
+ entity.getClass().getSimpleName().toLowerCase() + " (";
// 得到实际中的所有的get 开头的方法
List<Method> list = this.matchPojoMethods(entity, "get");
Iterator
<Method> iter = list.iterator();
Object obj[]
= new Object[list.size()];
int i = 0;
// 拼接字段顺序 insert into table name(id,name,email,
while (iter.hasNext()) {
Method method
= iter.next();
sql
+= method.getName().substring(3).toLowerCase() + ",";
// 对日期要做处理
if (method.getReturnType().getSimpleName().indexOf("Date") != -1) {
SimpleDateFormat sbf
= new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
obj[i]
= sbf.format(method.invoke(entity, new Object[] {}));
}
else {
obj[i]
= method.invoke(entity, new Object[] {});
}
i
++;
}
// 去掉最后一个,符号insert insert into table name(id,name,email) values(
sql = sql.substring(0, sql.lastIndexOf(",")) + ") values(";
// 拼装预编译SQL语句insert insert into table name(id,name,email) values(?,?,?,
for (int j = 0; j < list.size(); j++) {
sql
+= "?,";
}
// 去掉SQL语句最后一个,符号insert insert into table name(id,name,email)
// values(?,?,?);
sql = sql.substring(0, sql.lastIndexOf(",")) + ")";
// 到此SQL语句拼接完成,打印SQL语句
System.out.println(sql);
try {
this.prep = this.open_db().prepareStatement(sql);
//参数赋值
for (int j = 0; j < obj.length; j++) {
this.prep.setObject(j + 1, obj[j]);
}
//执行更新操作
result = this.prep.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
this.close_db();
}
return result;
}
/**
* 修改
*
*
@param entity
*
@return
*
@throws Exception
*/
public int updateMethod(T entity) throws Exception {

String sql
= "update "
+ entity.getClass().getSimpleName().toLowerCase() + " set ";
List
<Method> list = this.matchPojoMethods(entity, "get");
// 装载参数
Object obj[] = new Object[list.size()];
int i = 0;
// 临时Method对象,负责迭代时装method对象.
Method tempMethod = null;
// 由于修改时不需要修改ID,所以按顺序加参数则应该把Id移到最后.
Method idMethod = null;
Iterator
<Method> iter = list.iterator();
while (iter.hasNext()) {
tempMethod
= iter.next();
// 如果方法名中带有ID字符串并且长度为2,则视为ID.
if (tempMethod.getName().lastIndexOf("Id") != -1
&& tempMethod.getName().substring(3).length() == 2) {
obj[list.size()
- 1] = tempMethod.invoke(entity,
new Object[] {});
// 把ID字段的对象存放到一个变量中,然后在集合中删掉.
idMethod = tempMethod;
iter.remove();
// 如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为ID
} else if ((entity.getClass().getSimpleName() + "Id")
.equalsIgnoreCase(tempMethod.getName().substring(
3))) {
obj[list.size()
- 1] = tempMethod.invoke(entity,
new Object[] {});
idMethod
= tempMethod;
iter.remove();
}
}

// 把迭代指针移到第一位
iter = list.iterator();
while (iter.hasNext()) {
tempMethod
= iter.next();
sql
+= tempMethod.getName().substring(3).toLowerCase() + "= ?,";
obj[i]
= tempMethod.invoke(entity, new Object[] {});
i
++;
}
// 去掉最后一个,符号
sql = sql.substring(0, sql.lastIndexOf(","));
// 添加条件
sql += " where " + idMethod.getName().substring(3).toLowerCase()
+ " = ?";
// SQL拼接完成,打印SQL语句
System.out.println(sql);
this.prep = this.open_db().prepareStatement(sql);
for (int j = 0; j < obj.length; j++) {
this.prep.setObject(j + 1, obj[j]);
}
result
= this.prep.executeUpdate();
this.close_db();
return result;
}
/**
* 自动填充每一行的数据,到类中
*
@param currentRow 当前行
*
@param classEntity 类对象
*
@return
*/
public T autoFillEntity(ResultSet currentRow, Class<T> classEntity){
T entity
=null;
try {
// 通过类来实例化对象
entity = classEntity.newInstance();
// 存放Pojo(或被操作表)主键的方法对象
Method idMethod = null;

//得到该类中的所有的set方法
List<Method> list = this.matchPojoMethods(entity, "set");
//得到所有的set方法的迭代器
Iterator<Method> iter = list.iterator();

//遍历每一个类中的set方法
while (iter.hasNext()) {
Method method
= iter.next(); //取得方法对象
//如果这个 setXXX(Integer,Double,Date,String ,自定义对象 )
if (method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) {
// 由于list集合中,method对象取出的方法顺序与数据库字段顺序不一致(比如:list的第一个方法是setDate,而数据库按顺序取的是"123"值)
// 所以数据库字段采用名字对应的方式取.
this.setString(
method,
entity,
this.rst.getString(method.getName().substring(3).toLowerCase()));
}
else if (method.getParameterTypes()[0].getSimpleName()
.indexOf(
"Date") != -1) {
this.setDate(
method,
entity,
this.rst.getDate(method.getName().substring(3)
.toLowerCase()));
}
else if (method.getParameterTypes()[0].getSimpleName() .indexOf("Integer") != -1) {
this.setInt(
method,
entity,
this.rst.getInt(method.getName().substring(3)
.toLowerCase()));
}
else if (method.getParameterTypes()[0].getSimpleName() .indexOf("Double") != -1) {
this.setDouble(
method,
entity,
this.rst.getInt(method.getName().substring(3)
.toLowerCase()));
}
}
}
catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return entity;
}

/**
* 根据对象查询
*
*
@param object
*
@return
*
@throws Exception
*/
public T findById(Object object) throws Exception {
String sql
= "select * from "
+ persistentClass.getSimpleName().toLowerCase() + " where ";
// 通过子类的构造函数,获得参数化类型的具体类型.比如BaseDAO<T>也就是获得T的具体类型
T entity = persistentClass.newInstance();
// 存放Pojo(或被操作表)主键的方法对象
Method idMethod = null;
List
<Method> list = this.matchPojoMethods(entity, "set");
Iterator
<Method> iter = list.iterator();
// 过滤取得Method对象
while (iter.hasNext()) {
Method tempMethod
= iter.next();
if (tempMethod.getName().indexOf("Id") != -1
&& tempMethod.getName().substring(3).length() == 2) {
idMethod
= tempMethod;
break;
}
else if ((entity.getClass().getSimpleName() + "Id")
.equalsIgnoreCase(tempMethod.getName().substring(
3))) {
idMethod
= tempMethod;
break;
}
}


// 第一个字母转为小写
sql += idMethod.getName().substring(3, 4).toLowerCase()
+ idMethod.getName().substring(4) + " = ?";

System.out.println(sql);

this.prep = this.open_db().prepareStatement(sql);
// 判断id的类型
if (object instanceof Integer) {
this.prep.setInt(1, (Integer) object);
}
else if (object instanceof String) {
this.prep.setString(1, (String) object);
}
this.rst = this.prep.executeQuery();
// 把指针指向迭代器第一行
iter = list.iterator();
// 封装
while (this.rst.next()) {
while (iter.hasNext()) {
Method method
= iter.next();
if (method.getParameterTypes()[0].getSimpleName().indexOf(
"String") != -1) {
// 由于list集合中,method对象取出的方法顺序与数据库字段顺序不一致(比如:list的第一个方法是setDate,而数据库按顺序取的是"123"值)
// 所以数据库字段采用名字对应的方式取.
this.setString(
method,
entity,
this.rst.getString(method.getName().substring(3)
.toLowerCase()));
}
else if (method.getParameterTypes()[0].getSimpleName()
.indexOf(
"Date") != -1) {
this.setDate(
method,
entity,
this.rst.getDate(method.getName().substring(3)
.toLowerCase()));
}
else if (method.getParameterTypes()[0].getSimpleName()
.indexOf(
"Double") != -1){
this.setDouble(
method,
entity,
this.rst.getInt(method.getName().substring(3)
.toLowerCase()));
}
else if(method.getParameterTypes()[0].getSimpleName()
.indexOf(
"Integer") != -1){
this.setInt(
method,
entity,
this.rst.getInt(method.getName().substring(3)
.toLowerCase()));
}
}
}

this.close_db();
return entity;
}
/**
* 打开数据库
*
*
@return
*
@throws SQLException
*/
protected Connection open_db() throws SQLException {
this.conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return this.conn;
}
/**
* 关闭连接
*
*
@throws SQLException
*/
protected void close_db() throws SQLException {
if (this.rst != null) {
this.rst.close();
}
if (this.prep != null) {
this.prep.close();
}
if (this.conn != null) {
this.conn.close();
}
}
}