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============");
- }
- }