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包:
1.2.1.3 公共連庫幫助類ConnectionUtil類
- 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));
- }
- }
- }
- }
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接口類
- 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);
- }
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接口實現類
- 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;
- }
- }
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接口實現類
- 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;
- }
- }
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類
- 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";
- }
- }
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類型
- 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;
- }
- }
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類型
- 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;
- }
- }
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包:
1.2.2.2 Junit測試Jdbc
- package com.user.test;
- import java.util.List;
- import com.user.model.User;
- import com.user.service.UserService;
- import com.user.service.impl.UserServiceImpl;
- import com.user.vo.UserVO;
- import junit.framework.TestCase;
- /**
- * Junit測試
- * 使用JUnit,主要都是通過繼承TestCase類別來撰寫測試用例,使用testXXX()名稱來撰寫單元測試。
- * JUnit可以大量減少Java代碼中程序錯誤的個數,JUnit是一種流行的單元測試框架,用於在發佈代碼之前對其進行單元測試。
- * 使用JUnit好處:
- * 1.可以使測試代碼與產品代碼分開。
- * 2.針對某一個類的測試代碼通過較少的改動便可以應用於另一個類的測試。
- * 3.易於集成到測試人員的構建過程中,JUnit和Ant的結合可以實施增量開發。
- * 4.JUnit是公開源代碼的,可以進行二次開發。
- * 5.可以方便地對JUnit進行擴展。
- * @author yuanxw
- *
- */
- public class UserTest extends TestCase{
- private UserService userService = new UserServiceImpl();
- /**
- * 測試 查詢用戶列表
- */
- public void testSearchUser(){
- System.out.println("===========testSearchUser============");
- // 設置查詢條件
- UserVO userVo = new UserVO();
- userVo.setStartCreateTime("2013-07-24 17:40:16");
- userVo.setEndCreateTime("2013-08-27 11:25:27");
- // 從查詢頁碼
- int page = 1;
- // 顯示記錄數
- int maxRows = 10;
- // 排序屬性
- String sort = "userId";
- // 排序方式
- String order = "desc";
- // 用戶集合
- List<User> userList = userService.searchUser(userVo, page, maxRows, sort, order);
- if(userList != null && userList.size() > 0){
- for (User user : userList) {
- System.out.println("userId=====>" + user.getUserId());
- System.out.println("userName===>"+ user.getUserName());
- System.out.println("password===>"+ user.getPassword());
- System.out.println("sex========>"+ user.isSex());
- System.out.println("createTime=>"+ user.getCreateTime());
- System.out.println("updateTime=>"+ user.getUpdateTime());
- System.out.println("=====================================\r");
- }
- }
- System.out.println("===========testSearchUser============");
- }
- /**
- * 測試 條件查詢用戶數量
- */
- public void testGetCountUser(){
- System.out.println("===========testGetCountUser============");
- // 設置查詢條件
- UserVO userVo = new UserVO();
- userVo.setStartCreateTime("2013-07-24 17:40:16");
- userVo.setEndCreateTime("2013-08-27 11:25:27");
- long count= userService.getCountUser(userVo);
- System.out.println("count===>" + count);
- System.out.println("===========testGetCountUser============");
- }
- /**
- * 測試 獲得最大的用戶編號
- */
- public void testGetMaxUserId(){
- System.out.println("===========tetGetMaxUserId============");
- long maxId = userService.getMaxUserId();
- System.out.println("maxId===>" + maxId);
- System.out.println("===========tetGetMaxUserId============");
- }
- /**
- * 測試 根據用戶名查詢用戶count用戶個數
- */
- public void testGetUserCountByName(){
- System.out.println("===========testGetUserCountByName============");
- long count = userService.getUserCountByName("yuan_xw");
- System.out.println("count===>" + count);
- System.out.println("===========testGetUserCountByName============");
- }
- /**
- * 根據名稱獲得用戶對象
- * @param userName
- */
- public void testGetUserByName(){
- System.out.println("===========testGetUserByName============");
- User user = userService.getUserByName("yuan_xw");
- if(user != null){
- System.out.println("userId=====>" + user.getUserId());
- System.out.println("userName===>"+ user.getUserName());
- System.out.println("password===>"+ user.getPassword());
- System.out.println("sex========>"+ user.isSex());
- System.out.println("createTime=>"+ user.getCreateTime());
- System.out.println("updateTime=>"+ user.getUpdateTime());
- }
- System.out.println("===========testGetUserByName============");
- }
- /**
- * 測試 判斷用戶名是否唯一
- * 是唯一返回true,不是唯一返回false
- */
- public void testGetUniqueUserName(){
- System.out.println("===========testGetUniqueUserName============");
- boolean result = userService.getUniqueUserName("yuan_xw", "1");
- System.out.println("result===>" + result);
- System.out.println("===========testGetUniqueUserName============");
- }
- /**
- * 測試 根據用戶編號獲得用戶對象
- */
- public void testGetUserById(){
- System.out.println("===========testGetUserById============");
- User user = userService.getUserById("1");
- if(user != null){
- System.out.println("userId=====>" + user.getUserId());
- System.out.println("userName===>"+ user.getUserName());
- System.out.println("password===>"+ user.getPassword());
- System.out.println("sex========>"+ user.isSex());
- System.out.println("createTime=>"+ user.getCreateTime());
- System.out.println("updateTime=>"+ user.getUpdateTime());
- }
- System.out.println("===========testGetUserById============");
- }
- /**
- * 測試 保存用戶
- * 保存成功:true 保存失敗:false
- */
- public void testSaveUser(){
- System.out.println("===========testSaveUser============");
- // 獲得最大的用戶編號
- long maxId = userService.getMaxUserId();
- // 創建保存用戶
- UserVO userVO = new UserVO((int) (maxId+1), "test", "123456",
- false, "2013-09-12 22:54:29", "2013-09-12 22:54:29");
- // 保存用戶
- boolean result = userService.saveUser(userVO);
- System.out.println("result===>" + result);
- System.out.println("===========testSaveUser============");
- }
- /**
- * 測試 更新用戶
- * 更新成功:true 更新失敗:false
- */
- public void testUpdateUser(){
- System.out.println("===========testUpdateUser============");
- // 獲得最大的用戶編號
- long maxId = userService.getMaxUserId();
- // 創建修改用戶
- UserVO userVO = new UserVO((int) (maxId), "update_test", "999999",
- true, "2013-09-12 22:54:29", "2013-09-12 23:03:00");
- // 保存用戶
- boolean result = userService.updateUser(userVO);
- System.out.println("result===>" + result);
- System.out.println("===========testUpdateUser============");
- }
- /**
- * 測試 刪除用戶
- */
- public void testDeleteUser(){
- System.out.println("===========testDeleteUser============");
- // 用戶編號字符串,以“,”分隔
- long maxId = userService.getMaxUserId();
- String userIds = maxId+"";
- boolean result = userService.deleteUser(userIds);
- System.out.println("result===>" + result);
- System.out.println("===========testDeleteUser============");
- }
- }