Java-JDBC連接數據庫(MySQL)

1.1數據庫連接

Java 數據庫連接,(Java Database Connectivity,簡稱JDBC)是Java語言中用來規範客戶端程序如何來訪問數據庫的應用程序接口,提供了諸如查詢和更新數據庫中數據的方法。JDBC也是SunMicrosystems的商標[1]。它JDBC是面向關係型數據庫的。

1.1.1 Jdbc驅動程序共分四種類型

1.1.1.1 類型Jdbc-ODBC橋

1.      這種類型的驅動把所有JDBC的調用傳遞給ODBC,再讓後者調用數據庫本地驅動代碼(也就是數據庫廠商提供的數據庫操作二進制代碼庫,例如Oracle中的oci.dll)

優點:只要有對應的ODBC驅動(大部分數據庫廠商都會提供),幾乎可以訪問所有的數據庫。

缺點:執行效率比較低,不適合大數據量訪問的應用;由於需要客戶端預裝對應的ODBC驅動,不適合Internet/Intranet應用。

1.1.1.2 類型  本地驅動

2.      這種類型的驅動通過客戶端加載數據庫廠商提供的本地代碼庫(C/C++等)來訪問數據庫,而在驅動程序中則包含了Java代碼。

優點:速度快於第一類驅動(但仍比不上第3、第4類驅動)。

缺點:由於需要客戶端預裝對應的數據庫廠商代碼庫,仍不適合Internet/Intranet應用。

1.1.1.3 類型  網絡協議驅動

3.      這種類型的驅動給客戶端提供了一個網絡API,客戶端上的JDBC驅動程序使用套接字(Socket)來調用服務器上的中間件程序,後者在將其請求轉化爲所需的具體API調用。

優點:不需要在客戶端加載數據庫廠商提供的代碼庫,單個驅動程序可以對多個數據庫進行訪問,可擴展性較好。

缺點:在中間件層仍需對最終數據進行配置;由於多出一箇中間件層,速度不如第四類驅動程序。

1.1.1.4 類型本地協議驅動

4.      這種類型的驅動使用Socket,直接在客戶端和數據庫間通信。

優點:訪問速度最快;這是最直接、最純粹的Java實現。

                           缺點:因爲缺乏足夠的文檔和技術支持,幾乎只有數據庫廠商自己才能提供這種類型的JDBC驅動;需要針對不同的數據庫使用不同的驅動程序。 

1.2Jdbc連接數據庫

1.2.1 MySQL數據庫

1.2.1.1 表結構

1.      創建數據庫、表sql語句:

-- 設置數據庫編碼

SET NAMES gbk;

 

-- 創建數據庫

CREATE DATABASE jdbc;

 

-- 使用數據庫

USE jdbc;

 

-- 創建用戶表

CREATE TABLE USER(

    user_id INT(11) NOT NULL AUTO_INCREMENT,

    user_name VARCHAR(30),

    user_pass VARCHAR(30),

    user_sex CHAR(1),

    create_time VARCHAR(19),

    update_time VARCHAR(19),

    PRIMARYKEY(user_id)

);

2.      表結構如下圖所示:

字段名

說明

類型

備註

user_id

用戶編號

INT(11)

主鍵,自增,增值爲1

user_name

用戶名

VARCHAR(30)

 

user_pass

密碼

VARCHAR(30)

 

user_sex

性別

CHAR(1)

0:false 1:爲true

create_time

創建時間

VARCHAR(19)

 

update_time

更新時間

VARCHAR(19)

 

1.2.1.2 MySQL驅動

1.      MySQL驅動:mysql-connector-java-3.1.12-bin.jar

2.      Junit下載地址:http://www.mysql.com

3.      mysql-connector-java-3.1.12-bin.jar包:

mysql-connector-java-3.1.12-bin.jar

1.2.1.3  公共連庫幫助類ConnectionUtil類

  1. package com.common.util;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.ResultSetMetaData;  
  8. import java.sql.SQLException;  
  9. import java.sql.Statement;  
  10. import java.util.ArrayList;  
  11. import java.util.HashMap;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14.   
  15. public class ConnectionUtil {  
  16.     // 數據庫連接驅動  
  17.     public static final String DRIVER = "com.mysql.jdbc.Driver";  
  18.     // 數據庫連接URL  
  19.     public static final String URL = "jdbc:mysql://localhost:3306/jdbc";  
  20.     // 數據庫用戶名  
  21.     public static final String USER = "root";  
  22.     // 數據庫密碼  
  23.     public static final String PASS = "root";  
  24.   
  25.     /** 
  26.      * 獲得數據庫連接 
  27.      *  
  28.      * @return 
  29.      */  
  30.     public static Connection getConnection() {  
  31.         // 聲明Connection連接對象  
  32.         Connection conn = null;  
  33.         try {  
  34.             // 使用Class.forName()方法自動創建這個驅動程序的實例且自動調用DriverManager來註冊  
  35.             Class.forName(DRIVER);  
  36.             // 通過DriverManager的getConnection()方法獲取數據庫連接  
  37.             conn = DriverManager.getConnection(URL, USER, PASS);  
  38.         } catch (ClassNotFoundException e) {  
  39.             e.printStackTrace();  
  40.             System.out.println("數據庫驅動沒有找到!");  
  41.         } catch (SQLException e) {  
  42.             e.printStackTrace();  
  43.             System.out.println("數據庫連接失敗!");  
  44.         }  
  45.         return conn;  
  46.     }  
  47.   
  48.     /** 
  49.      * 關閉數據庫鏈接 
  50.      *  
  51.      * @param conn 
  52.      * @param statement 
  53.      * @param rs 
  54.      */  
  55.     public static void close(Connection conn, Statement statement, ResultSet rs) {  
  56.         // 關閉數據集  
  57.         if (rs != null) {  
  58.             try {  
  59.                 rs.close();  
  60.             } catch (SQLException e) {  
  61.                 e.printStackTrace();  
  62.             }  
  63.         }  
  64.   
  65.         // 關閉預處理對象  
  66.         if (statement != null) {  
  67.             try {  
  68.                 statement.close();  
  69.             } catch (SQLException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.   
  74.         // 關閉連接對象  
  75.         if (conn != null) {  
  76.             try {  
  77.                 if (!conn.isClosed()) {  
  78.                     conn.close();  
  79.                 }  
  80.             } catch (SQLException e) {  
  81.                 e.printStackTrace();  
  82.             }  
  83.         }  
  84.     }  
  85.   
  86.     /** 
  87.      * 查詢數據庫信息列表 
  88.      *  
  89.      * @param sql 
  90.      *            查詢數據的SQL語句 
  91.      * @param List<Object> params  參數 
  92.      * @return 
  93.      */  
  94.     public static List<Map<String, Object>> queryList(String sql, List<Object> params) {  
  95.         // 返回List數組  
  96.         List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();  
  97.         Map<String,Object> rows = null;  
  98.   
  99.         // 數據庫的連接(會話),對象  
  100.         Connection conn = null;  
  101.         // 預編譯的 SQL 語句的對象  
  102.         PreparedStatement statement = null;  
  103.         // 結果集  
  104.         ResultSet rs = null;  
  105.         try {  
  106.             conn = getConnection();  
  107.             // 創建PreparedStatement對象  
  108.             statement = conn.prepareStatement(sql);  
  109.             // 爲查詢語句設置參數  
  110.             setParameter(statement, params);  
  111.             // 獲得結果集  
  112.             rs = statement.executeQuery();  
  113.             // 獲得結果集的信息  
  114.             ResultSetMetaData rsmd = rs.getMetaData();  
  115.             // 獲得列的總數  
  116.             int columnCount = rsmd.getColumnCount();  
  117.             // 遍歷結果集  
  118.             while (rs.next()) {  
  119.                 rows = new HashMap<String, Object>();  
  120.                 for (int i = 0; i < columnCount; i++) {  
  121.                     // 獲得數據庫列名  
  122.                     String columnLalbe = rsmd.getColumnLabel(i+1);  
  123.                     rows.put(columnLalbe, rs.getObject(columnLalbe));  
  124.                 }  
  125.                 // 添加到  
  126.                 data.add(rows);  
  127.             }  
  128.         } catch (SQLException e) {  
  129.             e.printStackTrace();  
  130.             System.out.println("數據庫查詢出錯");  
  131.         } finally {  
  132.             ConnectionUtil.close(conn, statement, rs);  
  133.         }  
  134.         // 返回數組對象  
  135.         return data;  
  136.     }  
  137.       
  138.     /** 
  139.      * 查詢數據庫總紀錄數 
  140.      *  
  141.      * @param sql 
  142.      *            查詢數據的SQL語句 
  143.      * @param List<Object> params 參數 
  144.      * @return 
  145.      */  
  146.     public static long queryCount(String sql, List<Object> params) {  
  147.         // 定義返回記錄數  
  148.         long count = 0;  
  149.         // 數據庫的連接(會話),對象  
  150.         Connection conn = null;  
  151.         // 預編譯的 SQL 語句的對象  
  152.         PreparedStatement statement = null;  
  153.         // 結果集  
  154.         ResultSet rs = null;  
  155.         try {  
  156.             conn = getConnection();  
  157.             // 創建PreparedStatement對象  
  158.             statement = conn.prepareStatement(sql);  
  159.             // 爲查詢語句設置參數  
  160.             setParameter(statement, params);  
  161.             // 獲得結果集  
  162.             rs = statement.executeQuery();  
  163.             // 遍歷結果集  
  164.             while (rs.next()) {  
  165.                 count = rs.getLong(1);  
  166.             }  
  167.         } catch (SQLException e) {  
  168.             e.printStackTrace();  
  169.             System.out.println("數據庫查詢出錯");  
  170.         } finally {  
  171.             ConnectionUtil.close(conn, statement, rs);  
  172.         }  
  173.         // 返回數組對象  
  174.         return count;  
  175.     }  
  176.   
  177.     /** 
  178.      * 添加、修改、刪除 通用方法 
  179.      *  
  180.      * @param sql 
  181.      * @param List<Object> params 可變的參數 
  182.      * @return 返回值爲更新記錄數 
  183.      */  
  184.     public static int update(String sql, List<Object> params) {  
  185.         // 數據庫的連接(會話),對象  
  186.         Connection conn = null;  
  187.         // 預編譯的 SQL 語句的對象  
  188.         PreparedStatement statement = null;  
  189.         // 定義受影響的行數  
  190.         int rows = 0;  
  191.         try {  
  192.             // 獲得數庫連接  
  193.             conn = ConnectionUtil.getConnection();  
  194.             // 創建預編譯SQL對象  
  195.             statement = conn.prepareStatement(sql);  
  196.             // 設置SQL話句參數  
  197.             setParameter(statement, params);  
  198.             // 返回受影響的行數  
  199.             rows = statement.executeUpdate();  
  200.         } catch (SQLException e) {  
  201.             e.printStackTrace();  
  202.             System.out.println("數據庫操作異常!");  
  203.         }  
  204.         return rows;  
  205.     }  
  206.   
  207.     /** 
  208.      * 爲預編譯對象設置參數 
  209.      *  
  210.      * @param statement 
  211.      * @param object 
  212.      * @throws SQLException 
  213.      */  
  214.     public static void setParameter(PreparedStatement statement, List<Object> params) throws SQLException {  
  215.         if (params != null && params.size() > 0) {  
  216.             // 循環設置參數  
  217.             for (int i = 0; i < params.size(); i++) {  
  218.                 statement.setObject((i + 1), params.get(i));  
  219.             }  
  220.         }  
  221.     }  
  222. }  
package com.common.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;import 
java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConnectionUtil {	
// 數據庫連接驅動	
public static final String DRIVER = "com.mysql.jdbc.Driver";	
// 數據庫連接URL	
public static final String URL = "jdbc:mysql://localhost:3306/jdbc";	
// 數據庫用戶名	
public static final String USER = "root";	
// 數據庫密碼	
public static final String PASS = "root";	
/**	 * 獲得數據庫連接	 
* 	 * @return	
 */	
public static Connection getConnection() {		
// 聲明Connection連接對象		
Connection conn = null;		
try {			
// 使用Class.forName()方法自動創建這個驅動程序的實例且自動調用DriverManager來註冊			
Class.forName(DRIVER);			
// 通過DriverManager的getConnection()方法獲取數據庫連接			
conn = DriverManager.getConnection(URL, USER, PASS);		
} catch (ClassNotFoundException e) {			
e.printStackTrace();			
System.out.println("數據庫驅動沒有找到!");		
} catch (SQLException e) {			
e.printStackTrace();			
System.out.println("數據庫連接失敗!");		}		return conn;	}	
/**	 * 關閉數據庫鏈接	 * 	
 * @param conn	 * @param statement	 
* @param rs	 */	
public static void close(Connection conn, Statement statement, ResultSet rs) {		
// 關閉數據集		
if (rs != null) {			
try {				
      rs.close();			
} catch (SQLException e) {				
e.printStackTrace();			
}		
}		
// 關閉預處理對象		
if (statement != null) {			
  try {				
statement.close();			
} catch (SQLException e) {				
e.printStackTrace();			
}		
}		
// 關閉連接對象		
if (conn != null) {			
try {				
if (!conn.isClosed()) {					
conn.close();				}			
} catch (SQLException e) {				
e.printStackTrace();			
}		}	}	
/**	 
* 查詢數據庫信息列表	 * 	
 * @param sql	 *           
 查詢數據的SQL語句	 * @param List<Object> params  參數	 
* @return	 */	
public static List<Map<String, Object>> queryList(String sql, List<Object> params) {		
// 返回List數組		
List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();		
Map<String,Object> rows = null;		
// 數據庫的連接(會話),對象		
Connection conn = null;		
// 預編譯的 SQL 語句的對象		
PreparedStatement statement = null;		
// 結果集		
ResultSet rs = null;		
try {			
conn = getConnection();			
// 創建PreparedStatement對象			
statement = conn.prepareStatement(sql);			
// 爲查詢語句設置參數			
setParameter(statement, params);			
// 獲得結果集			
rs = statement.executeQuery();			
// 獲得結果集的信息			
ResultSetMetaData rsmd = rs.getMetaData();			
// 獲得列的總數			
int columnCount = rsmd.getColumnCount();			
// 遍歷結果集			
while (rs.next()) {				
rows = new HashMap<String, Object>();				
for (int i = 0; i < columnCount; i++) {					
// 獲得數據庫列名					
String columnLalbe = rsmd.getColumnLabel(i+1);					
rows.put(columnLalbe, rs.getObject(columnLalbe));				
}				
// 添加到				
data.add(rows);			
}		
} catch (SQLException e) {			
e.printStackTrace();			
System.out.println("數據庫查詢出錯");		
} finally {			
ConnectionUtil.close(conn, statement, rs);		}		
// 返回數組對象		
return data;	}		
/**	 * 查詢數據庫總紀錄數	 * 	 
* @param sql	 *            查詢數據的SQL語句	
 * @param List<Object> params 參數	 
* @return	 */	
public static long queryCount(String sql, List<Object> params) {		
// 定義返回記錄數		
long count = 0;		
// 數據庫的連接(會話),對象		
Connection conn = null;		
// 預編譯的 SQL 語句的對象		
PreparedStatement statement = null;		
// 結果集		
ResultSet rs = null;		
try {			
conn = getConnection();			
// 創建PreparedStatement對象			
statement = conn.prepareStatement(sql);			
// 爲查詢語句設置參數			
setParameter(statement, params);			
// 獲得結果集			
rs = statement.executeQuery();			
// 遍歷結果集			
while (rs.next()) {				
count = rs.getLong(1);			
}		
} catch (SQLException e) {			
e.printStackTrace();			
System.out.println("數據庫查詢出錯");		
} finally {			
ConnectionUtil.close(conn, statement, rs);		
}		
// 返回數組對象		
return count;	}	
 
/**	 * 添加、修改、刪除 通用方法	 * 	
 * @param sql	 * @param List<Object> params 可變的參數	 
* @return 返回值爲更新記錄數	 */	
public static int update(String sql, List<Object> params) {		
// 數據庫的連接(會話),對象		
Connection conn = null;		
// 預編譯的 SQL 語句的對象		
PreparedStatement statement = null;		
// 定義受影響的行數		
int rows = 0;		
try {			
// 獲得數庫連接			
conn = ConnectionUtil.getConnection();			
// 創建預編譯SQL對象			
statement = conn.prepareStatement(sql);			
// 設置SQL話句參數			
setParameter(statement, params);			
// 返回受影響的行數			
rows = statement.executeUpdate();		
} catch (SQLException e) {			
e.printStackTrace();			
System.out.println("數據庫操作異常!");		
}		return rows;	}	
/**	 * 爲預編譯對象設置參數	 * 	
 * @param statement	 * @param object	
 * @throws SQLException	 */	
public static void setParameter(PreparedStatement statement, List<Object> params) throws SQLException {		
if (params != null && params.size() > 0) {			
// 循環設置參數			
for (int i = 0; i < params.size(); i++) {				
statement.setObject((i + 1), params.get(i));			
}		
}	
}}

1.2.1.4 Dao層UserDao接口類

  1. package com.user.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.user.model.User;  
  6. import com.user.vo.UserVO;  
  7.   
  8. public interface UserDao {  
  9.       
  10.     /** 
  11.      * 查詢用戶列表 
  12.      * @param userVo    VO對象 
  13.      * @param page      頁數 
  14.      * @param maxRows   每頁顯示記數 
  15.      * @param sort      排序字段 
  16.      * @param order     排序方式(asc或desc) 
  17.      * @return  
  18.      */  
  19.     public List<User> searchUser(UserVO userVo, int page, int maxRows,  
  20.             String sort, String order);  
  21.       
  22.     /** 
  23.      * 或者用戶數量 
  24.      * @param userVo    VO對象 
  25.      * @return  
  26.      */  
  27.     public long getCountUser(UserVO userVo);  
  28.       
  29.     /** 
  30.      * 獲得最大的用戶編號 
  31.      * @return 
  32.      */  
  33.     public long getMaxUserId();  
  34.       
  35.     /** 
  36.      * 根據用戶名查詢用戶count用戶個數 
  37.      * @param userName 用戶名 
  38.      * @return 
  39.      */  
  40.     public long getUserCountByName(String userName);  
  41.       
  42.     /**  
  43.      * 根據名稱獲得用戶對象 
  44.      * @param userName 用戶名 
  45.      * @return 
  46.      */  
  47.     public User getUserByName(String userName);  
  48.       
  49.     /** 
  50.      * 判斷用戶名是否唯一 
  51.      * @param userName 
  52.      * @return 是唯一返回true,不是唯一返回false 
  53.      */  
  54.     public boolean getUniqueUserName(String userName,String userId);  
  55.       
  56.       
  57.     /** 
  58.      * 根據用戶編號獲得用戶對象 
  59.      * @param userId 用戶號 
  60.      * @return 
  61.      */  
  62.     public User getUserById(String userId);  
  63.       
  64.       
  65.     /** 
  66.      * 保存用戶 
  67.      * @param user 用戶對象 
  68.      * @return 
  69.      */  
  70.     public boolean saveUser(User user);  
  71.       
  72.     /** 
  73.      * 更新用戶 
  74.      * @param user 用戶對象 
  75.      * @return 
  76.      */  
  77.     public boolean updateUser(User user);  
  78.       
  79.     /** 
  80.      * 刪除用戶  
  81.      * @param userIds 用戶編號字符串,以“,”分隔 
  82.      * @return 
  83.      */  
  84.     public boolean deleteUser(String userIds);  
  85. }  
package com.user.dao;import java.util.List;import com.user.model.User;import com.user.vo.UserVO;public interface UserDao {		/**	 * 查詢用戶列表	 * @param userVo 	VO對象	 * @param page 		頁數	 * @param maxRows 	每頁顯示記數	 * @param sort 		排序字段	 * @param order 	排序方式(asc或desc)	 * @return 	 */	public List<User> searchUser(UserVO userVo, int page, int maxRows,			String sort, String order);		/**	 * 或者用戶數量	 * @param userVo 	VO對象	 * @return 	 */	public long getCountUser(UserVO userVo);		/**	 * 獲得最大的用戶編號	 * @return	 */	public long getMaxUserId();		/**	 * 根據用戶名查詢用戶count用戶個數	 * @param userName 用戶名	 * @return	 */	public long getUserCountByName(String userName);		/** 	 * 根據名稱獲得用戶對象	 * @param userName 用戶名	 * @return	 */	public User getUserByName(String userName);		/**	 * 判斷用戶名是否唯一	 * @param userName	 * @return 是唯一返回true,不是唯一返回false	 */	public boolean getUniqueUserName(String userName,String userId);			/**	 * 根據用戶編號獲得用戶對象	 * @param userId 用戶號	 * @return	 */	public User getUserById(String userId);			/**	 * 保存用戶	 * @param user 用戶對象	 * @return	 */	public boolean saveUser(User user);		/**	 * 更新用戶	 * @param user 用戶對象	 * @return	 */	public boolean updateUser(User user);		/**	 * 刪除用戶 	 * @param userIds 用戶編號字符串,以“,”分隔	 * @return	 */	public boolean deleteUser(String userIds);}

1.2.1.5 Dao層UserDaoImpl接口實現類

  1. package com.user.dao.impl;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.common.util.ConnectionUtil;  
  8. import com.common.util.StringUtil;  
  9. import com.user.dao.UserDao;  
  10. import com.user.model.User;  
  11. import com.user.util.UserBeanUtil;  
  12. import com.user.vo.UserVO;  
  13.   
  14. public class UserDaoImpl implements UserDao{  
  15.       
  16.     /** 
  17.      * 查詢用戶列表 
  18.      * @param userVo    VO對象 
  19.      * @param page      頁數 
  20.      * @param maxRows   每頁顯示記數 
  21.      * @param sort      排序字段 
  22.      * @param order     排序方式(asc或desc) 
  23.      * @return  
  24.      */  
  25.     public List<User> searchUser(UserVO userVo, int page, int maxRows,  
  26.             String sort, String order) {  
  27.   
  28.         StringBuffer sqlBuffer = new StringBuffer("select * from user where 1=1");  
  29.         // 添加參數  
  30.         List<Object> params = new ArrayList<Object>();  
  31.         if (userVo != null) {  
  32.             // 用戶名  
  33.             if (!StringUtil.isEmpty(userVo.getUserName())) {  
  34.                 sqlBuffer.append(" and user_name like ? ");  
  35.                 params.add("%" + userVo.getUserName() + "%");  
  36.             }  
  37.   
  38.             // 創建時間  
  39.             if (!StringUtil.isEmpty(userVo.getStartCreateTime())) {  
  40.                 sqlBuffer.append(" and create_time >=?");  
  41.                 params.add(userVo.getStartCreateTime());  
  42.             }  
  43.   
  44.             if (!StringUtil.isEmpty(userVo.getEndCreateTime())) {  
  45.                 sqlBuffer.append(" and create_time <=?");  
  46.                 params.add(userVo.getEndCreateTime());  
  47.             }  
  48.   
  49.             // 更新時間  
  50.             if (!StringUtil.isEmpty(userVo.getStartUpdateTime())) {  
  51.                 sqlBuffer.append(" and update_tiume >=?");  
  52.                 params.add(userVo.getStartUpdateTime());  
  53.             }  
  54.   
  55.             if (!StringUtil.isEmpty(userVo.getEndUpdateTime())) {  
  56.                 sqlBuffer.append(" and update_tiume <=?");  
  57.                 params.add(userVo.getEndUpdateTime());  
  58.             }  
  59.               
  60.             // 排序  
  61.             if(!StringUtil.isEmpty(sort) && !StringUtil.isEmpty(order)){  
  62.                 sqlBuffer.append(" order by ").append(UserBeanUtil.fieldToColumn(sort)).append(" ").append(order);  
  63.             }  
  64.               
  65.              // 分頁  
  66.              if(page > 0 && maxRows > 0){  
  67.                  // 公式:firstRows = (page - 1) * maxRows  
  68.                  int firstRows = (page - 1) * maxRows ;  
  69.                  sqlBuffer.append(" limit ").append(firstRows).append(",").append(maxRows);  
  70.              }  
  71.         }  
  72.           
  73.         // 查詢用戶列表  
  74.         List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(),params);  
  75.         return UserBeanUtil.copyProperty(datas);  
  76.     }  
  77.       
  78.     /** 
  79.      * 條件查詢用戶數量 
  80.      * @param userVo    VO對象 
  81.      * @return  
  82.      */  
  83.     public long getCountUser(UserVO userVo) {  
  84.          StringBuffer sqlBuffer = new StringBuffer("select count(user_id) from user where 1=1");  
  85.         // 添加參數  
  86.         List<Object> params = new ArrayList<Object>();  
  87.         if (userVo != null) {  
  88.             // 用戶名  
  89.             if (!StringUtil.isEmpty(userVo.getUserName())) {  
  90.                 sqlBuffer.append(" and user_name like ? ");  
  91.                 params.add("%" + userVo.getUserName() + "%");  
  92.             }  
  93.   
  94.             // 創建時間  
  95.             if (!StringUtil.isEmpty(userVo.getStartCreateTime())) {  
  96.                 sqlBuffer.append(" and create_time >=?");  
  97.                 params.add(userVo.getStartCreateTime());  
  98.             }  
  99.   
  100.             if (!StringUtil.isEmpty(userVo.getEndCreateTime())) {  
  101.                 sqlBuffer.append(" and create_time <=?");  
  102.                 params.add(userVo.getEndCreateTime());  
  103.             }  
  104.   
  105.             // 更新時間  
  106.             if (!StringUtil.isEmpty(userVo.getStartUpdateTime())) {  
  107.                 sqlBuffer.append(" and update_tiume >=?");  
  108.                 params.add(userVo.getStartUpdateTime());  
  109.             }  
  110.   
  111.             if (!StringUtil.isEmpty(userVo.getEndUpdateTime())) {  
  112.                 sqlBuffer.append(" and update_tiume <=?");  
  113.                 params.add(userVo.getEndUpdateTime());  
  114.             }  
  115.             // 返回總記錄數  
  116.             return ConnectionUtil.queryCount(sqlBuffer.toString(),params);  
  117.         }  
  118.         return 0;  
  119.     }  
  120.       
  121.     /** 
  122.      * 獲得最大的用戶編號 
  123.      * @return 
  124.      */  
  125.     public long getMaxUserId(){  
  126.         StringBuffer sqlBuffer = new StringBuffer("select max(user_id) from user;");  
  127.         return ConnectionUtil.queryCount(sqlBuffer.toString(), null);  
  128.     }  
  129.       
  130.     /** 
  131.      * 根據用戶名查詢用戶count用戶個數 
  132.      * @param userName 用戶名 
  133.      * @return 
  134.      */  
  135.     public long getUserCountByName(String userName){  
  136.         if(StringUtil.isEmpty(userName)){  
  137.             return Integer.MAX_VALUE;  
  138.         }  
  139.         // 接寫sql語句  
  140.         StringBuffer sqlBuffer = new StringBuffer("select count(user_id) from user where 1=1 and user_name = ?");  
  141.         // 添加參數  
  142.         List<Object> params = new ArrayList<Object>();  
  143.         params.add(userName);  
  144.         // 返回查詢的用  
  145.         return ConnectionUtil.queryCount(sqlBuffer.toString(), params);  
  146.     }  
  147.       
  148.     /**  
  149.      * 根據名稱獲得用戶對象 
  150.      * @param userName 用戶名 
  151.      * @return 
  152.      */  
  153.     public User getUserByName(String userName){  
  154.         if(StringUtil.isEmpty(userName)){  
  155.             return null;  
  156.         }  
  157.         // 接寫sql語句  
  158.         StringBuffer sqlBuffer = new StringBuffer("select * from user where 1=1 and user_name = ?");  
  159.         // 添加參數  
  160.         List<Object> params = new ArrayList<Object>();  
  161.         params.add(userName);  
  162.         // 查詢用戶列表  
  163.         List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(),params);  
  164.         List<User> userList = UserBeanUtil.copyProperty(datas);  
  165.   
  166.         // 返回user  
  167.         if(userList != null && userList.size() > 0){  
  168.             return userList.get(0);           
  169.         }  
  170.         return null;  
  171.     }  
  172.       
  173.     /** 
  174.      * 判斷用戶名是否唯一 
  175.      * @param userName 
  176.      * @return 是唯一返回true,不是唯一返回false 
  177.      */  
  178.     public boolean getUniqueUserName(String userName,String userId){  
  179.         // 參數爲空判斷   
  180.         if(StringUtil.isEmpty(userName)){  
  181.             return false;  
  182.         }  
  183.           
  184.         if(StringUtil.isEmpty(userId)){  
  185.             return false;  
  186.         }  
  187.           
  188.         // 接寫sql語句  
  189.         StringBuffer sqlBuffer = new StringBuffer("select count(*) from user where user_name = ? and user_id != ? ");  
  190.         // 添加參數  
  191.         List<Object> params = new ArrayList<Object>();  
  192.         params.add(userName);  
  193.         params.add(userId);  
  194.           
  195.         // 查詢用戶列表  
  196.         long count = ConnectionUtil.queryCount(sqlBuffer.toString(),params);  
  197.         return count <= 0 ? true : false;  
  198.     }   
  199.       
  200.       
  201.     /** 
  202.      * 根據用戶編號獲得用戶對象 
  203.      * @param userId 用戶號 
  204.      * @return 
  205.      */  
  206.     public User getUserById(String userId){  
  207.         // 爲空判斷  
  208.         if(StringUtil.isEmpty(userId)){  
  209.             return null;  
  210.         }  
  211.           
  212.         // 接接sql語句  
  213.         StringBuffer sqlBuffer = new StringBuffer("select * from user where user_id = ?");  
  214.           
  215.         // 添加參數  
  216.         List<Object> params = new ArrayList<Object>();  
  217.         params.add(userId);  
  218.           
  219.         // 查詢用戶  
  220.         List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(), params);  
  221.         List<User> userList = UserBeanUtil.copyProperty(datas);  
  222.           
  223.         if(userList != null && userList.size() > 0){  
  224.             return userList.get(0);           
  225.         }  
  226.         return null;  
  227.     }  
  228.       
  229.       
  230.     /** 
  231.      * 保存用戶 
  232.      * @param user 用戶對象 
  233.      * @return 
  234.      */  
  235.     public boolean saveUser(User user){  
  236.         // 用戶爲空判斷  
  237.         if(user == null){  
  238.             return false;  
  239.         }  
  240.           
  241.         // 拼接sql語句  
  242.         StringBuffer sqlBuffer = new StringBuffer("insert into user(user_id,user_name,user_pass,user_sex,create_time,update_time)");  
  243.         sqlBuffer.append("values(?,?,?,?,?,?)");  
  244.           
  245.         // 添加參數  
  246.         List<Object> params = new ArrayList<Object>();  
  247.           
  248.         // 用戶編號  
  249.         if(!StringUtil.isEmpty(user.getUserId()+"")){  
  250.             params.add(user.getUserId());  
  251.         }  
  252.           
  253.         // 用戶名  
  254.         if(!StringUtil.isEmpty(user.getUserName())){  
  255.             params.add(user.getUserName());  
  256.         }  
  257.           
  258.         // 密碼  
  259.         if(!StringUtil.isEmpty(user.getPassword())){  
  260.             params.add(user.getPassword());  
  261.         }  
  262.           
  263.         // 性別  
  264.         if(!StringUtil.isEmpty(user.isSex() + "")){  
  265.             params.add(user.isSex());  
  266.         }  
  267.           
  268.         // 創建時間  
  269.         if(!StringUtil.isEmpty(user.getCreateTime())){  
  270.             params.add(user.getCreateTime());  
  271.         }  
  272.           
  273.         // 更新時間  
  274.         if(!StringUtil.isEmpty(user.getUpdateTime())){  
  275.             params.add(user.getUpdateTime());  
  276.         }  
  277.           
  278.         // 判斷param.size參數的長度是否爲6,檢驗數填寫是否完成  
  279.         if(params.size() != 6){  
  280.             return false;  
  281.         }  
  282.         // 保存  
  283.         int result = ConnectionUtil.update(sqlBuffer.toString(), params);  
  284.         // 返回執行結果  
  285.         return result >= 1 ? true : false;  
  286.     }  
  287.       
  288.     /** 
  289.      * 更新用戶 
  290.      * @param user 用戶對象 
  291.      * @return 
  292.      */  
  293.     public boolean updateUser(User user){  
  294.         // 用戶爲空判斷  
  295.         if(user == null){  
  296.             return false;  
  297.         }  
  298.           
  299.         // 拼接sql語句  
  300.         StringBuffer sqlBuffer = new StringBuffer("update user set user_name=?,user_pass=?,user_sex=?,create_time=?,update_time=?");  
  301.         sqlBuffer.append(" where user_id=?");  
  302.         // 添加參數  
  303.         List<Object> params = new ArrayList<Object>();  
  304.           
  305.         // 用戶名  
  306.         if(!StringUtil.isEmpty(user.getUserName())){  
  307.             params.add(user.getUserName());  
  308.         }  
  309.           
  310.         // 密碼  
  311.         if(!StringUtil.isEmpty(user.getPassword())){  
  312.             params.add(user.getPassword());  
  313.         }  
  314.           
  315.         // 性別  
  316.         if(!StringUtil.isEmpty(user.isSex() + "")){  
  317.             params.add(user.isSex());  
  318.         }  
  319.           
  320.         // 創建時間  
  321.         if(!StringUtil.isEmpty(user.getCreateTime())){  
  322.             params.add(user.getCreateTime());  
  323.         }  
  324.           
  325.         // 更新時間  
  326.         if(!StringUtil.isEmpty(user.getUpdateTime())){  
  327.             params.add(user.getUpdateTime());  
  328.         }  
  329.           
  330.         // 用戶編號  
  331.         if(!StringUtil.isEmpty(user.getUserId()+"")){  
  332.             params.add(user.getUserId());  
  333.         }  
  334.           
  335.         // 判斷param.size參數的長度是否爲6,檢驗數填寫是否完成  
  336.         if(params.size() != 6){  
  337.             return false;  
  338.         }  
  339.         // 保存  
  340.         int result = ConnectionUtil.update(sqlBuffer.toString(), params);  
  341.         // 返回執行結果  
  342.         return result >= 1 ? true : false;  
  343.     }  
  344.       
  345.     /** 
  346.      * 刪除用戶  
  347.      * @param userIds 用戶編號字符串,以“,”分隔 
  348.      * @return 
  349.      */  
  350.     public boolean deleteUser(String userIds){  
  351.         // 判斷id是否存在  
  352.         if(StringUtil.isEmpty(userIds)){  
  353.             return false;  
  354.         }  
  355.           
  356.         // 添加參數  
  357.         StringBuffer idsBuffer = new StringBuffer("");  
  358.         List<Object> params = new ArrayList<Object>();  
  359.           
  360.         String [] ids = userIds.split(",");  
  361.         if(ids == null || ids.length < 0){  
  362.             return false;  
  363.         }  
  364.           
  365.         for(int i = 0;i<ids.length;i++){  
  366.             idsBuffer.append("?,");  
  367.             params.add(ids[i]);  
  368.         }  
  369.           
  370.         // 拼寫sql語句  
  371.         StringBuffer sqlBuffer = new StringBuffer("delete from user where user_id in (");  
  372.         sqlBuffer.append(idsBuffer.substring(0, idsBuffer.length()-1)).append(")");  
  373.           
  374.         // 執行刪除操作  
  375.         int result = ConnectionUtil.update(sqlBuffer.toString(), params);  
  376.         return result >0 ? true : false;  
  377.     }  
  378. }  
package com.user.dao.impl;import java.util.ArrayList;import java.util.List;import java.util.Map;import com.common.util.ConnectionUtil;import com.common.util.StringUtil;import com.user.dao.UserDao;import com.user.model.User;import com.user.util.UserBeanUtil;import com.user.vo.UserVO;public class UserDaoImpl implements UserDao{		/**	 * 查詢用戶列表	 * @param userVo 	VO對象	 * @param page 		頁數	 * @param maxRows 	每頁顯示記數	 * @param sort 		排序字段	 * @param order 	排序方式(asc或desc)	 * @return 	 */	public List<User> searchUser(UserVO userVo, int page, int maxRows,			String sort, String order) {		StringBuffer sqlBuffer = new StringBuffer("select * from user where 1=1");		// 添加參數		List<Object> params = new ArrayList<Object>();		if (userVo != null) {			// 用戶名			if (!StringUtil.isEmpty(userVo.getUserName())) {				sqlBuffer.append(" and user_name like ? ");				params.add("%" + userVo.getUserName() + "%");			}			// 創建時間			if (!StringUtil.isEmpty(userVo.getStartCreateTime())) {				sqlBuffer.append(" and create_time >=?");				params.add(userVo.getStartCreateTime());			}			if (!StringUtil.isEmpty(userVo.getEndCreateTime())) {				sqlBuffer.append(" and create_time <=?");				params.add(userVo.getEndCreateTime());			}			// 更新時間			if (!StringUtil.isEmpty(userVo.getStartUpdateTime())) {				sqlBuffer.append(" and update_tiume >=?");				params.add(userVo.getStartUpdateTime());			}			if (!StringUtil.isEmpty(userVo.getEndUpdateTime())) {				sqlBuffer.append(" and update_tiume <=?");				params.add(userVo.getEndUpdateTime());			}						// 排序			if(!StringUtil.isEmpty(sort) && !StringUtil.isEmpty(order)){				sqlBuffer.append(" order by ").append(UserBeanUtil.fieldToColumn(sort)).append(" ").append(order);			}						 // 分頁			 if(page > 0 && maxRows > 0){				 // 公式:firstRows = (page - 1) * maxRows				 int firstRows = (page - 1) * maxRows ;				 sqlBuffer.append(" limit ").append(firstRows).append(",").append(maxRows);			 }		}				// 查詢用戶列表		List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(),params);		return UserBeanUtil.copyProperty(datas);	}		/**	 * 條件查詢用戶數量	 * @param userVo 	VO對象	 * @return 	 */	public long getCountUser(UserVO userVo) {		 StringBuffer sqlBuffer = new StringBuffer("select count(user_id) from user where 1=1");		// 添加參數		List<Object> params = new ArrayList<Object>();		if (userVo != null) {			// 用戶名			if (!StringUtil.isEmpty(userVo.getUserName())) {				sqlBuffer.append(" and user_name like ? ");				params.add("%" + userVo.getUserName() + "%");			}			// 創建時間			if (!StringUtil.isEmpty(userVo.getStartCreateTime())) {				sqlBuffer.append(" and create_time >=?");				params.add(userVo.getStartCreateTime());			}			if (!StringUtil.isEmpty(userVo.getEndCreateTime())) {				sqlBuffer.append(" and create_time <=?");				params.add(userVo.getEndCreateTime());			}			// 更新時間			if (!StringUtil.isEmpty(userVo.getStartUpdateTime())) {				sqlBuffer.append(" and update_tiume >=?");				params.add(userVo.getStartUpdateTime());			}			if (!StringUtil.isEmpty(userVo.getEndUpdateTime())) {				sqlBuffer.append(" and update_tiume <=?");				params.add(userVo.getEndUpdateTime());			}			// 返回總記錄數			return ConnectionUtil.queryCount(sqlBuffer.toString(),params);		}		return 0;	}		/**	 * 獲得最大的用戶編號	 * @return	 */	public long getMaxUserId(){		StringBuffer sqlBuffer = new StringBuffer("select max(user_id) from user;");		return ConnectionUtil.queryCount(sqlBuffer.toString(), null);	}		/**	 * 根據用戶名查詢用戶count用戶個數	 * @param userName 用戶名	 * @return	 */	public long getUserCountByName(String userName){		if(StringUtil.isEmpty(userName)){			return Integer.MAX_VALUE;		}		// 接寫sql語句		StringBuffer sqlBuffer = new StringBuffer("select count(user_id) from user where 1=1 and user_name = ?");		// 添加參數		List<Object> params = new ArrayList<Object>();		params.add(userName);		// 返回查詢的用		return ConnectionUtil.queryCount(sqlBuffer.toString(), params);	}		/** 	 * 根據名稱獲得用戶對象	 * @param userName 用戶名	 * @return	 */	public User getUserByName(String userName){		if(StringUtil.isEmpty(userName)){			return null;		}		// 接寫sql語句		StringBuffer sqlBuffer = new StringBuffer("select * from user where 1=1 and user_name = ?");		// 添加參數		List<Object> params = new ArrayList<Object>();		params.add(userName);		// 查詢用戶列表		List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(),params);		List<User> userList = UserBeanUtil.copyProperty(datas);		// 返回user		if(userList != null && userList.size() > 0){			return userList.get(0);					}		return null;	}		/**	 * 判斷用戶名是否唯一	 * @param userName	 * @return 是唯一返回true,不是唯一返回false	 */	public boolean getUniqueUserName(String userName,String userId){		// 參數爲空判斷 		if(StringUtil.isEmpty(userName)){			return false;		}				if(StringUtil.isEmpty(userId)){			return false;		}				// 接寫sql語句		StringBuffer sqlBuffer = new StringBuffer("select count(*) from user where user_name = ? and user_id != ? ");		// 添加參數		List<Object> params = new ArrayList<Object>();		params.add(userName);		params.add(userId);				// 查詢用戶列表		long count = ConnectionUtil.queryCount(sqlBuffer.toString(),params);		return count <= 0 ? true : false;	} 			/**	 * 根據用戶編號獲得用戶對象	 * @param userId 用戶號	 * @return	 */	public User getUserById(String userId){		// 爲空判斷		if(StringUtil.isEmpty(userId)){			return null;		}				// 接接sql語句		StringBuffer sqlBuffer = new StringBuffer("select * from user where user_id = ?");				// 添加參數		List<Object> params = new ArrayList<Object>();		params.add(userId);				// 查詢用戶		List<Map<String, Object>> datas = ConnectionUtil.queryList(sqlBuffer.toString(), params);		List<User> userList = UserBeanUtil.copyProperty(datas);				if(userList != null && userList.size() > 0){			return userList.get(0);					}		return null;	}			/**	 * 保存用戶	 * @param user 用戶對象	 * @return	 */	public boolean saveUser(User user){		// 用戶爲空判斷		if(user == null){			return false;		}				// 拼接sql語句		StringBuffer sqlBuffer = new StringBuffer("insert into user(user_id,user_name,user_pass,user_sex,create_time,update_time)");		sqlBuffer.append("values(?,?,?,?,?,?)");				// 添加參數		List<Object> params = new ArrayList<Object>();				// 用戶編號		if(!StringUtil.isEmpty(user.getUserId()+"")){			params.add(user.getUserId());		}				// 用戶名		if(!StringUtil.isEmpty(user.getUserName())){			params.add(user.getUserName());		}				// 密碼		if(!StringUtil.isEmpty(user.getPassword())){			params.add(user.getPassword());		}				// 性別		if(!StringUtil.isEmpty(user.isSex() + "")){			params.add(user.isSex());		}				// 創建時間		if(!StringUtil.isEmpty(user.getCreateTime())){			params.add(user.getCreateTime());		}				// 更新時間		if(!StringUtil.isEmpty(user.getUpdateTime())){			params.add(user.getUpdateTime());		}				// 判斷param.size參數的長度是否爲6,檢驗數填寫是否完成		if(params.size() != 6){			return false;		}		// 保存		int result = ConnectionUtil.update(sqlBuffer.toString(), params);		// 返回執行結果		return result >= 1 ? true : false;	}		/**	 * 更新用戶	 * @param user 用戶對象	 * @return	 */	public boolean updateUser(User user){		// 用戶爲空判斷		if(user == null){			return false;		}				// 拼接sql語句		StringBuffer sqlBuffer = new StringBuffer("update user set user_name=?,user_pass=?,user_sex=?,create_time=?,update_time=?");		sqlBuffer.append(" where user_id=?");		// 添加參數		List<Object> params = new ArrayList<Object>();				// 用戶名		if(!StringUtil.isEmpty(user.getUserName())){			params.add(user.getUserName());		}				// 密碼		if(!StringUtil.isEmpty(user.getPassword())){			params.add(user.getPassword());		}				// 性別		if(!StringUtil.isEmpty(user.isSex() + "")){			params.add(user.isSex());		}				// 創建時間		if(!StringUtil.isEmpty(user.getCreateTime())){			params.add(user.getCreateTime());		}				// 更新時間		if(!StringUtil.isEmpty(user.getUpdateTime())){			params.add(user.getUpdateTime());		}				// 用戶編號		if(!StringUtil.isEmpty(user.getUserId()+"")){			params.add(user.getUserId());		}				// 判斷param.size參數的長度是否爲6,檢驗數填寫是否完成		if(params.size() != 6){			return false;		}		// 保存		int result = ConnectionUtil.update(sqlBuffer.toString(), params);		// 返回執行結果		return result >= 1 ? true : false;	}		/**	 * 刪除用戶 	 * @param userIds 用戶編號字符串,以“,”分隔	 * @return	 */	public boolean deleteUser(String userIds){		// 判斷id是否存在		if(StringUtil.isEmpty(userIds)){			return false;		}				// 添加參數		StringBuffer idsBuffer = new StringBuffer("");		List<Object> params = new ArrayList<Object>();				String [] ids = userIds.split(",");		if(ids == null || ids.length < 0){			return false;		}				for(int i = 0;i<ids.length;i++){			idsBuffer.append("?,");			params.add(ids[i]);		}				// 拼寫sql語句		StringBuffer sqlBuffer = new StringBuffer("delete from user where user_id in (");		sqlBuffer.append(idsBuffer.substring(0, idsBuffer.length()-1)).append(")");				// 執行刪除操作		int result = ConnectionUtil.update(sqlBuffer.toString(), params);		return result >0 ? true : false;	}}

1.2.1.6 Service層UserService接口類

1.      Service層的UserService接口代碼和Dao層UserDao接口代碼一樣,可以直接複製過去,此處,不再寫重複代碼。

1.2.1.7 Service層UserServiceImpl接口實現類

  1. package com.user.service.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.user.dao.UserDao;  
  6. import com.user.dao.impl.UserDaoImpl;  
  7. import com.user.model.User;  
  8. import com.user.service.UserService;  
  9. import com.user.vo.UserVO;  
  10.   
  11.   
  12. public class UserServiceImpl implements UserService{  
  13.       
  14.     private UserDao userDao = new UserDaoImpl();  
  15.   
  16.     /** 
  17.      * 查詢用戶列表 
  18.      * @param userVo    VO對象 
  19.      * @param page      頁數 
  20.      * @param maxRows   每頁顯示記數 
  21.      * @param sort      排序字段 
  22.      * @param order     排序方式(asc或desc) 
  23.      * @return  
  24.      */  
  25.     public List<User> searchUser(UserVO userVo, int page, int maxRows,  
  26.             String sort, String order){  
  27.         return userDao.searchUser(userVo, page, maxRows, sort, order);  
  28.     }  
  29.       
  30.     /** 
  31.      * 或者用戶數量 
  32.      * @param userVo    VO對象 
  33.      * @return  
  34.      */  
  35.     public long getCountUser(UserVO userVo){  
  36.         return userDao.getCountUser(userVo);  
  37.     }  
  38.       
  39.     /** 
  40.      * 獲得最大的用戶編號 
  41.      * @return 
  42.      */  
  43.     public long getMaxUserId(){  
  44.         return userDao.getMaxUserId();  
  45.     }  
  46.       
  47.     /** 
  48.      * 根據用戶名查詢用戶count用戶個數 
  49.      * @param userName 用戶名 
  50.      * @return 
  51.      */  
  52.     public long getUserCountByName(String userName){  
  53.         return userDao.getUserCountByName(userName);  
  54.     }  
  55.       
  56.     /**  
  57.      * 根據名稱獲得用戶對象 
  58.      * @param userName 用戶名 
  59.      * @return 
  60.      */  
  61.     public User getUserByName(String userName){  
  62.         return userDao.getUserByName(userName);  
  63.     }  
  64.       
  65.     /** 
  66.      * 判斷用戶名是否唯一 
  67.      * @param userName 
  68.      * @return 是唯一返回true,不是唯一返回false 
  69.      */  
  70.     public boolean getUniqueUserName(String userName,String userId){  
  71.         return userDao.getUniqueUserName(userName, userId);  
  72.     }  
  73.       
  74.       
  75.     /** 
  76.      * 根據用戶編號獲得用戶對象 
  77.      * @param userId 用戶號 
  78.      * @return 
  79.      */  
  80.     public User getUserById(String userId){  
  81.         return userDao.getUserById(userId);  
  82.     }  
  83.       
  84.       
  85.     /** 
  86.      * 保存用戶 
  87.      * @param user 用戶對象 
  88.      * @return 
  89.      */  
  90.     public boolean saveUser(User user){  
  91.         return userDao.saveUser(user);  
  92.     }  
  93.       
  94.     /** 
  95.      * 更新用戶 
  96.      * @param user 用戶對象 
  97.      * @return 
  98.      */  
  99.     public boolean updateUser(User user){  
  100.         return userDao.updateUser(user);  
  101.     }  
  102.       
  103.     /** 
  104.      * 刪除用戶  
  105.      * @param userIds 用戶編號字符串,以“,”分隔 
  106.      * @return 
  107.      */  
  108.     public boolean deleteUser(String userIds){  
  109.         return userDao.deleteUser(userIds);  
  110.     }  
  111.   
  112.   
  113.     /** 
  114.      * userDao 對象 getter方法 ... 
  115.      * @return 
  116.      */  
  117.     public UserDao getUserDao() {  
  118.         return userDao;  
  119.     }  
  120.       
  121.     /** 
  122.      * userDao 對象 setter方法 ... 
  123.      * @return 
  124.      */  
  125.     public void setUserDao(UserDao userDao) {  
  126.         this.userDao = userDao;  
  127.     }  
  128. }  
package com.user.service.impl;import java.util.List;import com.user.dao.UserDao;import com.user.dao.impl.UserDaoImpl;import com.user.model.User;import com.user.service.UserService;import com.user.vo.UserVO;public class UserServiceImpl implements UserService{		private UserDao userDao = new UserDaoImpl();	/**	 * 查詢用戶列表	 * @param userVo 	VO對象	 * @param page 		頁數	 * @param maxRows 	每頁顯示記數	 * @param sort 		排序字段	 * @param order 	排序方式(asc或desc)	 * @return 	 */	public List<User> searchUser(UserVO userVo, int page, int maxRows,			String sort, String order){		return userDao.searchUser(userVo, page, maxRows, sort, order);	}		/**	 * 或者用戶數量	 * @param userVo 	VO對象	 * @return 	 */	public long getCountUser(UserVO userVo){		return userDao.getCountUser(userVo);	}		/**	 * 獲得最大的用戶編號	 * @return	 */	public long getMaxUserId(){		return userDao.getMaxUserId();	}		/**	 * 根據用戶名查詢用戶count用戶個數	 * @param userName 用戶名	 * @return	 */	public long getUserCountByName(String userName){		return userDao.getUserCountByName(userName);	}		/** 	 * 根據名稱獲得用戶對象	 * @param userName 用戶名	 * @return	 */	public User getUserByName(String userName){		return userDao.getUserByName(userName);	}		/**	 * 判斷用戶名是否唯一	 * @param userName	 * @return 是唯一返回true,不是唯一返回false	 */	public boolean getUniqueUserName(String userName,String userId){		return userDao.getUniqueUserName(userName, userId);	}			/**	 * 根據用戶編號獲得用戶對象	 * @param userId 用戶號	 * @return	 */	public User getUserById(String userId){		return userDao.getUserById(userId);	}			/**	 * 保存用戶	 * @param user 用戶對象	 * @return	 */	public boolean saveUser(User user){		return userDao.saveUser(user);	}		/**	 * 更新用戶	 * @param user 用戶對象	 * @return	 */	public boolean updateUser(User user){		return userDao.updateUser(user);	}		/**	 * 刪除用戶 	 * @param userIds 用戶編號字符串,以“,”分隔	 * @return	 */	public boolean deleteUser(String userIds){		return userDao.deleteUser(userIds);	}	/**	 * userDao 對象 getter方法 ...	 * @return	 */	public UserDao getUserDao() {		return userDao;	}		/**	 * userDao 對象 setter方法 ...	 * @return	 */	public void setUserDao(UserDao userDao) {		this.userDao = userDao;	}}

1.2.1.8 User類型幫助類UserBeanUtil類

  1. package com.user.util;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.user.model.User;  
  8.   
  9. /** 
  10.  * 用戶實體 
  11.  */  
  12. public class UserBeanUtil {  
  13.     /** 
  14.      * 拷貝屬性值,返回對象列表 
  15.      * @param datas 
  16.      * @return 
  17.      */  
  18.     public static List<User> copyProperty(List<Map<String, Object>> datas){  
  19.         // 返回的用戶列表  
  20.         List<User> userList = new ArrayList<User>();  
  21.         if(datas != null && datas.size() > 0){  
  22.             for (Map<String, Object> map : datas) {  
  23.                 // map 爲判斷  
  24.                 if(!map.isEmpty()){  
  25.                     //遍歷map  
  26.                     User user = new User();  
  27.                     for(Map.Entry<String, Object> entry : map.entrySet()){  
  28.                         if("user_id".equals(entry.getKey())){  
  29.                             user.setUserId(Integer.parseInt(entry.getValue()+""));  
  30.                         }  
  31.                           
  32.                         if("user_name".equals(entry.getKey())){  
  33.                             user.setUserName(entry.getValue()+"");  
  34.                         }  
  35.                           
  36.                         if("user_pass".equals(entry.getKey())){  
  37.                             user.setPassword(entry.getValue()+"");  
  38.                         }  
  39.                           
  40.                         if("user_sex".equals(entry.getKey())){  
  41.                             user.setSex((entry.getValue()+"").equals("0") ? false : true);  
  42.                         }  
  43.                           
  44.                         if("create_time".equals(entry.getKey())){  
  45.                             user.setCreateTime(entry.getValue()+"");  
  46.                         }  
  47.                           
  48.                         if("update_time".equals(entry.getKey())){  
  49.                             user.setUpdateTime(entry.getValue()+"");  
  50.                         }  
  51.                     }  
  52.                     userList.add(user);  
  53.                 }  
  54.             }  
  55.         }  
  56.         return userList;  
  57.     }  
  58.       
  59.     /** 
  60.      * 字段名轉化爲列名(注:如果使用ORM映射框架,將不在需要該方法) 
  61.      * @param field  
  62.      * @return  
  63.      */  
  64.     public static String fieldToColumn(String field){  
  65.         // 用戶編號  
  66.         if("userId".equals(field)){  
  67.             return "user_id";  
  68.         }  
  69.           
  70.         // 用戶名  
  71.         if("userName".equals(field)){  
  72.             return "user_name";  
  73.         }  
  74.           
  75.         // 密碼  
  76.         if("password".equals(field)){  
  77.             return "user_pass";  
  78.         }  
  79.           
  80.         // 性別  
  81.         if("sex".equals(field)){  
  82.             return "user_sex";  
  83.         }  
  84.           
  85.         // 創建時間  
  86.         if("createTime".equals(field)){  
  87.             return "create_time";  
  88.         }  
  89.         // 更新時間  
  90.         if("updateTime".equals(field)){  
  91.             return "update_time";  
  92.         }  
  93.         return "user_id";  
  94.     }  
  95. }  
package com.user.util;import java.util.ArrayList;import java.util.List;import java.util.Map;import com.user.model.User;/** * 用戶實體 */public class UserBeanUtil {	/**	 * 拷貝屬性值,返回對象列表	 * @param datas	 * @return	 */	public static List<User> copyProperty(List<Map<String, Object>> datas){		// 返回的用戶列表		List<User> userList = new ArrayList<User>();		if(datas != null && datas.size() > 0){			for (Map<String, Object> map : datas) {				// map 爲判斷				if(!map.isEmpty()){					//遍歷map					User user = new User();					for(Map.Entry<String, Object> entry : map.entrySet()){						if("user_id".equals(entry.getKey())){							user.setUserId(Integer.parseInt(entry.getValue()+""));						}												if("user_name".equals(entry.getKey())){							user.setUserName(entry.getValue()+"");						}												if("user_pass".equals(entry.getKey())){							user.setPassword(entry.getValue()+"");						}												if("user_sex".equals(entry.getKey())){							user.setSex((entry.getValue()+"").equals("0") ? false : true);						}												if("create_time".equals(entry.getKey())){							user.setCreateTime(entry.getValue()+"");						}												if("update_time".equals(entry.getKey())){							user.setUpdateTime(entry.getValue()+"");						}					}					userList.add(user);				}			}		}		return userList;	}		/**	 * 字段名轉化爲列名(注:如果使用ORM映射框架,將不在需要該方法)	 * @param field 	 * @return 	 */	public static String fieldToColumn(String field){		// 用戶編號		if("userId".equals(field)){			return "user_id";		}				// 用戶名		if("userName".equals(field)){			return "user_name";		}				// 密碼		if("password".equals(field)){			return "user_pass";		}				// 性別		if("sex".equals(field)){			return "user_sex";		}				// 創建時間		if("createTime".equals(field)){			return "create_time";		}		// 更新時間		if("updateTime".equals(field)){			return "update_time";		}		return "user_id";	}}

1.2.1.9 實體類User類型

  1. package com.user.model;  
  2.   
  3. /** 
  4.  * 用戶 實體類 
  5.  * PO:持久對象,與數據庫中的表相映射的user對象 
  6.  * @author aebiz 
  7.  */  
  8. public class User {  
  9.     // 用戶編號  
  10.     private int userId;  
  11.     // 用戶名  
  12.     private String userName;  
  13.     // 密碼  
  14.     private String password;  
  15.     // 性別 0:false 1:爲true  
  16.     private boolean sex;  
  17.     // 創建時間  
  18.     private String createTime;  
  19.     // 更新時間  
  20.     private String updateTime;  
  21.       
  22.       
  23.     /** 
  24.      *  無參構造函數 
  25.      */  
  26.     public User() {  
  27.         super();  
  28.     }  
  29.   
  30.     /** 
  31.      * 全參構造函數 
  32.      * @param userId 
  33.      * @param userName 
  34.      * @param password 
  35.      * @param sex 
  36.      * @param createTime 
  37.      * @param updateTime 
  38.      */  
  39.     public User(int userId, String userName, String password, boolean sex,  
  40.             String createTime, String updateTime) {  
  41.         super();  
  42.         this.userId = userId;  
  43.         this.userName = userName;  
  44.         this.password = password;  
  45.         this.sex = sex;  
  46.         this.createTime = createTime;  
  47.         this.updateTime = updateTime;  
  48.     }  
  49.   
  50.     public int getUserId() {  
  51.         return userId;  
  52.     }  
  53.   
  54.     public void setUserId(int userId) {  
  55.         this.userId = userId;  
  56.     }  
  57.   
  58.     public String getUserName() {  
  59.         return userName;  
  60.     }  
  61.   
  62.     public void setUserName(String userName) {  
  63.         this.userName = userName;  
  64.     }  
  65.   
  66.     public String getPassword() {  
  67.         return password;  
  68.     }  
  69.   
  70.     public void setPassword(String password) {  
  71.         this.password = password;  
  72.     }  
  73.   
  74.     public boolean isSex() {  
  75.         return sex;  
  76.     }  
  77.   
  78.     public void setSex(boolean sex) {  
  79.         this.sex = sex;  
  80.     }  
  81.   
  82.     public String getCreateTime() {  
  83.         return createTime;  
  84.     }  
  85.   
  86.     public void setCreateTime(String createTime) {  
  87.         this.createTime = createTime;  
  88.     }  
  89.   
  90.     public String getUpdateTime() {  
  91.         return updateTime;  
  92.     }  
  93.   
  94.     public void setUpdateTime(String updateTime) {  
  95.         this.updateTime = updateTime;  
  96.     }  
  97. }  
package com.user.model;/** * 用戶 實體類 * PO:持久對象,與數據庫中的表相映射的user對象 * @author aebiz */public class User {	// 用戶編號	private int userId;	// 用戶名	private String userName;	// 密碼	private String password;	// 性別 0:false 1:爲true	private boolean sex;	// 創建時間	private String createTime;	// 更新時間	private String updateTime;			/**	 *  無參構造函數	 */	public User() {		super();	}	/**	 * 全參構造函數	 * @param userId	 * @param userName	 * @param password	 * @param sex	 * @param createTime	 * @param updateTime	 */	public User(int userId, String userName, String password, boolean sex,			String createTime, String updateTime) {		super();		this.userId = userId;		this.userName = userName;		this.password = password;		this.sex = sex;		this.createTime = createTime;		this.updateTime = updateTime;	}	public int getUserId() {		return userId;	}	public void setUserId(int userId) {		this.userId = userId;	}	public String getUserName() {		return userName;	}	public void setUserName(String userName) {		this.userName = userName;	}	public String getPassword() {		return password;	}	public void setPassword(String password) {		this.password = password;	}	public boolean isSex() {		return sex;	}	public void setSex(boolean sex) {		this.sex = sex;	}	public String getCreateTime() {		return createTime;	}	public void setCreateTime(String createTime) {		this.createTime = createTime;	}	public String getUpdateTime() {		return updateTime;	}	public void setUpdateTime(String updateTime) {		this.updateTime = updateTime;	}}

1.2.1.10 業務層之間的數據傳遞UserVO類型

  1. package com.user.vo;  
  2.   
  3. import com.user.model.User;  
  4. /** 
  5.  * UserVO 
  6.  * OV:value object值對象,VO用在商業邏輯層和表示層。 
  7.  * 各層操作屬於該層自己的數據對象,這樣就可以降低各層之間的耦合,便於以後系統的維護和擴展。 
  8.  * @author yuanxw 
  9.  * 
  10.  */  
  11. public class UserVO extends User {  
  12.     // 開始時間  
  13.     private String startCreateTime;  
  14.     // 結束時間  
  15.     private String endCreateTime;  
  16.   
  17.     // 開始更新時間  
  18.     private String startUpdateTime;  
  19.     // 結束更新時間  
  20.     private String endUpdateTime;  
  21.       
  22.     /** 
  23.      * 空構造函數 
  24.      */  
  25.     public UserVO() {  
  26.         super();  
  27.     }  
  28.   
  29.     /** 
  30.      * User父類全參構造函數 
  31.      * @param userId 
  32.      * @param userName 
  33.      * @param password 
  34.      * @param sex 
  35.      * @param createTime 
  36.      * @param updateTime 
  37.      */  
  38.     public UserVO(int userId, String userName, String password, boolean sex,  
  39.             String createTime, String updateTime) {  
  40.         this.setUserId(userId);  
  41.         this.setUserName(userName);  
  42.         this.setPassword(password);  
  43.         this.setSex(sex);  
  44.         this.setCreateTime(createTime);  
  45.         this.setUpdateTime(updateTime);  
  46.     }  
  47.       
  48.   
  49.     public String getStartCreateTime() {  
  50.         return startCreateTime;  
  51.     }  
  52.   
  53.     public void setStartCreateTime(String startCreateTime) {  
  54.         this.startCreateTime = startCreateTime;  
  55.     }  
  56.   
  57.     public String getEndCreateTime() {  
  58.         return endCreateTime;  
  59.     }  
  60.   
  61.     public void setEndCreateTime(String endCreateTime) {  
  62.         this.endCreateTime = endCreateTime;  
  63.     }  
  64.   
  65.     public String getStartUpdateTime() {  
  66.         return startUpdateTime;  
  67.     }  
  68.   
  69.     public void setStartUpdateTime(String startUpdateTime) {  
  70.         this.startUpdateTime = startUpdateTime;  
  71.     }  
  72.   
  73.     public String getEndUpdateTime() {  
  74.         return endUpdateTime;  
  75.     }  
  76.   
  77.     public void setEndUpdateTime(String endUpdateTime) {  
  78.         this.endUpdateTime = endUpdateTime;  
  79.     }  
  80. }  
package com.user.vo;import com.user.model.User;/** * UserVO * OV:value object值對象,VO用在商業邏輯層和表示層。 * 各層操作屬於該層自己的數據對象,這樣就可以降低各層之間的耦合,便於以後系統的維護和擴展。 * @author yuanxw * */public class UserVO extends User {	// 開始時間	private String startCreateTime;	// 結束時間	private String endCreateTime;	// 開始更新時間	private String startUpdateTime;	// 結束更新時間	private String endUpdateTime;		/**	 * 空構造函數	 */	public UserVO() {		super();	}	/**	 * User父類全參構造函數	 * @param userId	 * @param userName	 * @param password	 * @param sex	 * @param createTime	 * @param updateTime	 */	public UserVO(int userId, String userName, String password, boolean sex,			String createTime, String updateTime) {		this.setUserId(userId);		this.setUserName(userName);		this.setPassword(password);		this.setSex(sex);		this.setCreateTime(createTime);		this.setUpdateTime(updateTime);	}		public String getStartCreateTime() {		return startCreateTime;	}	public void setStartCreateTime(String startCreateTime) {		this.startCreateTime = startCreateTime;	}	public String getEndCreateTime() {		return endCreateTime;	}	public void setEndCreateTime(String endCreateTime) {		this.endCreateTime = endCreateTime;	}	public String getStartUpdateTime() {		return startUpdateTime;	}	public void setStartUpdateTime(String startUpdateTime) {		this.startUpdateTime = startUpdateTime;	}	public String getEndUpdateTime() {		return endUpdateTime;	}	public void setEndUpdateTime(String endUpdateTime) {		this.endUpdateTime = endUpdateTime;	}}

1.2.2 JDBC單元測試

1.2.2.1 Junit概述

1.     JUnit就是爲Java程序開發者實現單元測試提供一種框架,使得Java單元測試更規範有效,並且更有利於測試的集成。

2.      Junit下載地址:http://junit.org/

3.      Junit-4.11.jar最新jar包:

Junit-4.11.jar

1.2.2.2 Junit測試Jdbc

  1. package com.user.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.user.model.User;  
  6. import com.user.service.UserService;  
  7. import com.user.service.impl.UserServiceImpl;  
  8. import com.user.vo.UserVO;  
  9.   
  10. import junit.framework.TestCase;  
  11.   
  12. /** 
  13.  * Junit測試 
  14.  * 使用JUnit,主要都是通過繼承TestCase類別來撰寫測試用例,使用testXXX()名稱來撰寫單元測試。 
  15.  * JUnit可以大量減少Java代碼中程序錯誤的個數,JUnit是一種流行的單元測試框架,用於在發佈代碼之前對其進行單元測試。 
  16.  * 使用JUnit好處: 
  17.  * 1.可以使測試代碼與產品代碼分開。 
  18.  * 2.針對某一個類的測試代碼通過較少的改動便可以應用於另一個類的測試。 
  19.  * 3.易於集成到測試人員的構建過程中,JUnit和Ant的結合可以實施增量開發。 
  20.  * 4.JUnit是公開源代碼的,可以進行二次開發。 
  21.  * 5.可以方便地對JUnit進行擴展。 
  22.  * @author yuanxw 
  23.  * 
  24.  */  
  25. public class UserTest extends TestCase{  
  26.     private UserService userService = new UserServiceImpl();  
  27.       
  28.     /** 
  29.      * 測試  查詢用戶列表 
  30.      */  
  31.     public void testSearchUser(){  
  32.         System.out.println("===========testSearchUser============");  
  33.         // 設置查詢條件  
  34.         UserVO userVo = new UserVO();  
  35.         userVo.setStartCreateTime("2013-07-24 17:40:16");  
  36.         userVo.setEndCreateTime("2013-08-27 11:25:27");  
  37.           
  38.         // 從查詢頁碼  
  39.         int page = 1;  
  40.         // 顯示記錄數  
  41.         int maxRows = 10;  
  42.           
  43.         // 排序屬性  
  44.         String sort = "userId";  
  45.         // 排序方式  
  46.         String order = "desc";  
  47.         // 用戶集合  
  48.         List<User> userList = userService.searchUser(userVo, page, maxRows, sort, order);  
  49.         if(userList != null && userList.size() > 0){  
  50.             for (User user : userList) {  
  51.                 System.out.println("userId=====>" + user.getUserId());  
  52.                 System.out.println("userName===>"+ user.getUserName());  
  53.                 System.out.println("password===>"+ user.getPassword());  
  54.                 System.out.println("sex========>"+ user.isSex());  
  55.                 System.out.println("createTime=>"+ user.getCreateTime());  
  56.                 System.out.println("updateTime=>"+ user.getUpdateTime());  
  57.                 System.out.println("=====================================\r");  
  58.             }  
  59.         }  
  60.         System.out.println("===========testSearchUser============");  
  61.     }  
  62.       
  63.     /** 
  64.      * 測試  條件查詢用戶數量 
  65.      */  
  66.     public void testGetCountUser(){  
  67.         System.out.println("===========testGetCountUser============");  
  68.         // 設置查詢條件  
  69.         UserVO userVo = new UserVO();  
  70.         userVo.setStartCreateTime("2013-07-24 17:40:16");  
  71.         userVo.setEndCreateTime("2013-08-27 11:25:27");  
  72.           
  73.         long count= userService.getCountUser(userVo);  
  74.         System.out.println("count===>" + count);  
  75.         System.out.println("===========testGetCountUser============");  
  76.     }  
  77.     /** 
  78.      * 測試  獲得最大的用戶編號 
  79.      */  
  80.     public void testGetMaxUserId(){  
  81.         System.out.println("===========tetGetMaxUserId============");  
  82.         long maxId = userService.getMaxUserId();  
  83.         System.out.println("maxId===>" + maxId);  
  84.         System.out.println("===========tetGetMaxUserId============");  
  85.     }  
  86.   
  87.   
  88.     /** 
  89.      * 測試  根據用戶名查詢用戶count用戶個數 
  90.      */  
  91.     public void testGetUserCountByName(){  
  92.         System.out.println("===========testGetUserCountByName============");  
  93.         long count = userService.getUserCountByName("yuan_xw");  
  94.         System.out.println("count===>" + count);  
  95.         System.out.println("===========testGetUserCountByName============");  
  96.     }  
  97.       
  98.     /** 
  99.      * 根據名稱獲得用戶對象 
  100.      * @param userName 
  101.      */  
  102.     public void testGetUserByName(){  
  103.         System.out.println("===========testGetUserByName============");  
  104.         User user = userService.getUserByName("yuan_xw");  
  105.         if(user != null){  
  106.             System.out.println("userId=====>" + user.getUserId());  
  107.             System.out.println("userName===>"+ user.getUserName());  
  108.             System.out.println("password===>"+ user.getPassword());  
  109.             System.out.println("sex========>"+ user.isSex());  
  110.             System.out.println("createTime=>"+ user.getCreateTime());  
  111.             System.out.println("updateTime=>"+ user.getUpdateTime());  
  112.         }  
  113.         System.out.println("===========testGetUserByName============");  
  114.     }  
  115.       
  116.     /** 
  117.      * 測試  判斷用戶名是否唯一 
  118.      * 是唯一返回true,不是唯一返回false 
  119.      */  
  120.     public void testGetUniqueUserName(){  
  121.         System.out.println("===========testGetUniqueUserName============");  
  122.         boolean result = userService.getUniqueUserName("yuan_xw", "1");  
  123.         System.out.println("result===>" + result);  
  124.         System.out.println("===========testGetUniqueUserName============");  
  125.     }  
  126.       
  127.     /** 
  128.      * 測試  根據用戶編號獲得用戶對象 
  129.      */  
  130.     public void testGetUserById(){  
  131.         System.out.println("===========testGetUserById============");  
  132.         User user = userService.getUserById("1");  
  133.         if(user != null){  
  134.             System.out.println("userId=====>" + user.getUserId());  
  135.             System.out.println("userName===>"+ user.getUserName());  
  136.             System.out.println("password===>"+ user.getPassword());  
  137.             System.out.println("sex========>"+ user.isSex());  
  138.             System.out.println("createTime=>"+ user.getCreateTime());  
  139.             System.out.println("updateTime=>"+ user.getUpdateTime());  
  140.         }  
  141.         System.out.println("===========testGetUserById============");  
  142.     }  
  143.     /** 
  144.      * 測試  保存用戶 
  145.      * 保存成功:true 保存失敗:false 
  146.      */  
  147.     public void testSaveUser(){  
  148.         System.out.println("===========testSaveUser============");  
  149.         // 獲得最大的用戶編號  
  150.         long maxId = userService.getMaxUserId();  
  151.           
  152.         // 創建保存用戶  
  153.         UserVO userVO = new UserVO((int) (maxId+1), "test", "123456",  
  154.             false, "2013-09-12 22:54:29", "2013-09-12 22:54:29");  
  155.         // 保存用戶  
  156.         boolean result = userService.saveUser(userVO);  
  157.         System.out.println("result===>" + result);  
  158.         System.out.println("===========testSaveUser============");  
  159.     }  
  160.       
  161.     /** 
  162.      * 測試  更新用戶 
  163.      * 更新成功:true 更新失敗:false 
  164.      */  
  165.     public void testUpdateUser(){  
  166.         System.out.println("===========testUpdateUser============");  
  167.         // 獲得最大的用戶編號  
  168.         long maxId = userService.getMaxUserId();  
  169.           
  170.         // 創建修改用戶  
  171.         UserVO userVO = new UserVO((int) (maxId), "update_test", "999999",  
  172.                 true, "2013-09-12 22:54:29", "2013-09-12 23:03:00");  
  173.         // 保存用戶  
  174.         boolean result = userService.updateUser(userVO);  
  175.         System.out.println("result===>" + result);  
  176.         System.out.println("===========testUpdateUser============");  
  177.     }  
  178.       
  179.     /** 
  180.      * 測試  刪除用戶  
  181.      */  
  182.     public void testDeleteUser(){  
  183.         System.out.println("===========testDeleteUser============");  
  184.         // 用戶編號字符串,以“,”分隔  
  185.         long maxId = userService.getMaxUserId();  
  186.         String userIds = maxId+"";  
  187.         boolean result = userService.deleteUser(userIds);  
  188.         System.out.println("result===>" + result);  
  189.         System.out.println("===========testDeleteUser============");  
  190.     }  
  191. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章