筆記之_java整理框架

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
二、log4j配置,虛擬路徑src/main/resource下新建log4j.properties文件存放配置內容
三、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英文文檔修改
六、因爲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();
        }
    }
}
相關文章
相關標籤/搜索