您的位置:首页 > 其它

客户信息管理系统3—客户信息的增加(二)

2017-10-18 17:13 344 查看
客户信息管理系统3—客户信息的增加(二)
1.4.4 CustomersService(业务层):insert方法
package com.zhku.jsj144.zk.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.zhku.jsj144.zk.dao.CustomersDao;
import com.zhku.jsj144.zk.daoImpl.CustomersDaoImplement;
import com.zhku.jsj144.zk.domain.Customers;
import com.zhku.jsj144.zk.domain.PageBean;
import com.zhku.jsj144.zk.utils.DaoFactory;
import com.zhku.jsj144.zk.utils.JdbcUtils;
import com.zhku.jsj144.zk.utils.TransactionUtils;

public class CustomersService {

//解耦合技术 [反射技术+配置文件+接口]
//对比分析:
//以前代码耦合的时候:写代码是直接new对象,那么需要以来具体的类,如果没有这些具体的类,这
//么这个业务层默认的程序员就没有办法继续做开发
//现在,解耦合:引入了接口,通过接口去引用了返回的实现类,将来实现类有了之后,只需要将实现类集成进来,
//然后配置文件修改以下即可,不用再去修改源代码了。

private CustomersDao CustomersDao=DaoFactory.getInstance().createDao(CustomersDao.class);
// private CustomersDao CustomersDao=new CustomersDao();
public int insert(Customers customers){
// CustomersDao CustomersDao=new CustomersDao();

// CustomersDao CustomersDao;
// try {
// CustomersDao = (CustomersDao) DaoFactory.getDao();//解耦合技术获得
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
int count = CustomersDao.insert(customers);
return count;
}

//查询所有用户信息
public List selectAll() {
List resultList=CustomersDao.selectAll();//查询结果集
return resultList;
}

//删除一条记录,一个客户的信息
public void deleteOne(String id) {
CustomersDao.deleteOne(id);
}

// //批量删除
// public void deleteAll(String[] choose) {
// //开启事务处理,循环进行删除,每次删除一条记录,如果删除失败,则进行回滚事务,否则,最后进行提交事务,并关闭资源
//
// //问题思考:Connection对象应该出现待在dao层,而不应该出现在service层,这样导致service层和到层耦合了
// //思考:如何进行解耦呢?
// //这样Service层就不会使用dao层才会使用的Connection对象了。
// //方法:ThreadLocal类[线程本地类]的使用,可以解决这个问题
//
//
// //开启事务,需要获得Connection对象
// Connection con=null;
// try {
// con=JdbcUtils.getDatasourse().getConnection();//获得连接对象
// con.setAutoCommit(false);//开启事务
//
// for(int i=0;i<choose.length;i++){
// //手动管理事务,要自己传递Connection对象过去,确保Connection是唯一的
// CustomersDao.deleteOneTransaction(con,choose[i]);//每次删除一条记录
// }
// con.commit();//提交事务
// } catch (SQLException e) {
// try {
// con.rollback();//回滚事务
// } catch (SQLException e1) {
// e1.printStackTrace();
// }
// throw new RuntimeException("批量删除失败");
// }
// }

//完善后的deleteAll(String[] choose)方法
//批量删除
public void deleteAll(String[] choose) {
//开启事务处理,循环进行删除,每次删除一条记录,如果删除失败,则进行回滚事务,否则,最后进行提交事务,并关闭资源

//确保同一个线程使用的始终是同一个Connection对象
try{
//开启事务
TransactionUtils.startTransaction();
//批量删除操作
for(int i=0;i<choose.length;i++){
//手动管理事务,要自己传递Connection对象过去,确保Connection是唯一的
CustomersDao.deleteOneTransaction2(choose[i]);//每次删除一条记录
}
//提交事务
TransactionUtils.commit();
}catch(Exception e){
TransactionUtils.rollback();//回滚操作
throw new RuntimeException("批量删除失败...");
}finally{
//释放资源
TransactionUtils.relase();
}
}

public Customers getUpdateInfo(String id) {
Customers customers=CustomersDao.getUpdateInfo(id);
return customers;
}

public void update(Customers customers) {
CustomersDao.update(customers);
}

public List selectCondition(String conditionName, String keyWords) {
List customersList=CustomersDao.selectCondition(conditionName,keyWords);
return customersList;
}

//分页查询业务逻辑,目的获取分页pageBean的5个信息
//分页推导公式:
//1. 总页数=(总记录数+每页记录数-1)/每页记录数
//2. 初始索引=(当前页数-1)*每页记录数
public PageBean pageQuery(String num) {

int totalRecord=CustomersDao.selectAllCount();//总记录数
int pageRecord=10;//每页记录数【默认是每页10条记录】
int totalPage=(totalRecord+pageRecord-1)/pageRecord;//总页数
int currentPage=Integer.parseInt(num);//当前页数

//主要是初始索引参数,以及每页的记录数作为参数
int start=(currentPage-1)*pageRecord;//开始索引
List<Customers> dataList=CustomersDao.selectPageList(start,pageRecord);//当前页记录数

//将pageBean的信息封装起来
PageBean pageBean=new PageBean();
pageBean.setTotalPage(totalPage);
pageBean.setTotalRecord(totalRecord);
pageBean.setPageRecord(pageRecord);
pageBean.setCurrentPage(currentPage);
pageBean.setDataList(dataList);

return pageBean;
}
}

1.4.5 CustomersDao(dao层接口):insert方法
package com.zhku.jsj144.zk.dao;

import java.sql.Connection;
import java.util.List;

import org.junit.Test;

import com.zhku.jsj144.zk.domain.Customers;
//将Dao层抽象成一个接口,然后再写它的实现类
//目的:为了Service层与Dao层的解耦合。
//原因:每次Service调用一个方法,都要new一个Dao层对象,这样,就增加了Service层和Dao层的耦合性
//因此,通过书写接口,然后书写配置文件,利用反射技术,得到Dao层的对象,而不用每次new对象
//好处:提高了扩展性。

//应用场景:解耦合【接口+配置文件+反射技术】
// 某个模块不会写,自己可以定义一个接口,然后外包给别人去实现,利用解耦合技术,然后把别人实现好的方法,即:接口的实现类
//继承进来,在进行书写相应的配置文件,即可达成目的

public interface CustomersDao {

//插入用户信息
public abstract int insert(Customers customers);

//查询用户信息
public abstract List selectAll();

//删除一条记录
public abstract void deleteOne(String id);

//删除一条记录,并手动管理事务
public abstract void deleteOneTransaction(Connection con,String id);

//删除一条记录,并手动管理事务[写法2]
public abstract void deleteOneTransaction2(String id);

//查询一条用户记录信息,用于修改使用
public abstract Customers getUpdateInfo(String id);

//修改一条用户记录信息
public abstract void update(Customers customers);

//条件查询
public abstract List selectCondition(String conditionName, String keyWords);

//查找总记录个数
public abstract int selectAllCount();

//分页查询
public abstract List<Customers> selectPageList(int start, int pageRecord);

}

1.4.6 CustomersDaoImplement(dao层接口实现类):insert方法
package com.zhku.jsj144.zk.daoImpl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import com.zhku.jsj144.zk.dao.CustomersDao;
import com.zhku.jsj144.zk.domain.Customers;
import com.zhku.jsj144.zk.utils.JdbcUtils;
import com.zhku.jsj144.zk.utils.TransactionUtils;

public class CustomersDaoImplement implements CustomersDao {

//插入用户信息
/* (non-Javadoc)
* @see com.zhku.jsj144.zk.dao.CustomersDao#insert(com.zhku.jsj144.zk.domain.Customers)
*/
@Override
public int insert(Customers customers){
//调用工具类进行插入操作
// QueryRunner qr=new QueryRunner();//没有获取连接
try{
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());

//id,用UUID工具进行生成
String id=getId();

//参数数组
Object[] params=new Object[]{id,customers.getName(),customers.getGender(),
customers.getBirthday(),customers.getEmail(),customers.getCellphone(),
customers.getPreference(),customers.getType(),customers.getDescription()};

int count = qr.update("insert into customers values(?,?,?,?,?,?,?,?,?)", params);
System.out.println("count:"+count);
return count;//返回插入结果
}catch(SQLException e){
throw new RuntimeException(e);
}

}

//生成并获取id
private String getId(){
String id=UUID.randomUUID().toString();
id=id.replace("-", "");
return id;
}

//查询用户信息
/* (non-Javadoc)
* @see com.zhku.jsj144.zk.dao.CustomersDao#selectAll()
*/
@Override
public List selectAll() {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
try {
//返回查询结果集
List resultList = qr.query("select * from customers", new BeanListHandler(Customers.class));
return resultList;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

//删除一条记录
/* (non-Javadoc)
* @see com.zhku.jsj144.zk.dao.CustomersDao#deleteOne(java.lang.String)
*/
@Override
public void deleteOne(String id) {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
try {
qr.update("delete from customers where id=?", id);
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}

}

//删除一条记录,并手动管理事务
@Override
public void deleteOneTransaction(Connection con,String id) {
QueryRunner qr=new QueryRunner();
try {
qr.update(con,"delete from customers where id=?", id);
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//删除一条记录,并手动管理事务[写法2]
@Override
public void deleteOneTransaction2(String id) {
QueryRunner qr=new QueryRunner();
try {
//ThreadLocal类【线程本地类】的使用:确保同一个线程使用的始终是同一个Connection对象
qr.update(TransactionUtils.getConnection(),"delete from customers where id=?", id);
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//查询一条用户记录信息,用于修改使用
@Override
public Customers getUpdateInfo(String id) {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
Customers customers=null;
try {
customers = qr.query("select * from customers where id=?", new BeanHandler(Customers.class),id);
return customers;
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//修改一条用户记录信息
@Override
public void update(Customers customers) {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
Object[] params={customers.getName(),customers.getGender(),customers.getBirthday(),
customers.getCellphone(),customers.getEmail(),customers.getPreference(),
customers.getType(),customers.getDescription(),customers.getId()};
try {
qr.update("update customers set name=?,gender=?,birthday=?,cellphone=?,email=?,"
+ "preference=?,type=?,description=? where id=?", params);
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//条件查询
@Override
public List selectCondition(String conditionName, String keyWords) {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
try {
//select * from customers where name like '% 张 %'
List customersList=qr.query("select * from customers where "+conditionName+" like ?", new BeanListHandler(Customers.class),"%"+keyWords+"%");
return customersList;
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//查找总记录个数
@Override
public int selectAllCount() {
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
try {
// //异常:java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
// int count = (Integer) qr.query("select count(*) from customers", new ScalarHandler());

long count = (Long) qr.query("select count(*) from customers", new ScalarHandler());
return (int)count;//此处再强制转换
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

//分页查询
// 物理分页
// 在sql查询时,从数据库只检索分页需要的数据
// mysql物理分页,采用limit关键字
// 例如:检索11-20条 select * from user limit 10,10 ;
@Override
public List<Customers> selectPageList(int start, int pageRecord) {
//参数:初始索引,每页的记录数
QueryRunner qr=new QueryRunner(JdbcUtils.getDatasourse());
try {
//eg: select * from user limit 10,10 ;
List<Customers> pageList = qr.query("select * from customers limit ?,?", new BeanListHandler(Customers.class),start,pageRecord);
return pageList;
} catch (SQLException e) {
throw new RuntimeException(e);//抛出运行时异常
}
}

}

1.4.7 DaoFactory(dao层工厂)
package com.zhku.jsj144.zk.utils;

import java.util.ResourceBundle;
//用于创建到的工厂类
//工厂类很多时候会被弄成单例模式

public class DaoFactory {

private DaoFactory(){};
//一个工厂类实例
private static DaoFactory instance=new DaoFactory();
//获取工厂类实例
public static DaoFactory getInstance(){
return instance;
}

//用于返回传进来的一个类的实例对象出去
public <T> T createDao(Class<T> t){
//CustomerDao.class --> CustomerDao
String simpleName=t.getSimpleName();//获取自己吗对象的名字
//读取一个配置文件
//CustomersDao=com.zhku.jsj144.zk.daoImpl.CustomersDaoImplement
String clazzName=ResourceBundle.getBundle("dao").getString(simpleName);

try {
return (T)Class.forName(clazzName).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}

}

/*
* 自己写的方法
*
public static Object getDao(){

ResourceBundle bundle=ResourceBundle.getBundle("dao");//读取dao.properties配置文件
//配置文件内容:CustomersDao=com.zhku.jsj144.zk.daoImpl.CustomersDaoImplement
//左边:接口  右边:接口的实现类
String implClass=bundle.getString("CustomersDao");

//通过类的字符串名,利用反射,创建实例对象
Class<?> clazz;
try {
clazz = Class.forName(implClass);
Object instance = clazz.newInstance();//实例对象
return instance;//返回创建的实例对象:CustomersDaoImplement实例对象
} catch (Exception e) {
throw new RuntimeException(e);
}
}
*/
}


1.4.8 dao.properties(dao相关配置文件)

CustomersDao=com.zhku.jsj144.zk.daoImpl.CustomersDaoImplement


说明:

左边的键是:dao接口,右边的值是:dao接口的实现类

目的:

在service层调用dao工厂的一个方法:创建工厂实例方法去得到一个dao的实现类的一个实例,首先,读取到dao.properties配置文件里的dao和dao实现类的数值,然后获取后,通过反射技术,创建出这样的一个实例(dao接口实现类的实例)来。

1.4.9 JdbcUtils(工具类)               
package com.zhku.jsj144.zk.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
/*
* 工具类
* 1、获得数据源【c3p0】
* 2、获得c3p0连接池中的一个连接
*/
public class JdbcUtils {

private static DataSource ds=new ComboPooledDataSource();//数据库连接池的数据源

public static DataSource getDatasourse(){
return ds;//返回数据库连接池的数据源
}
public Connection getConnection() throws SQLException{
return ds.getConnection();//从数据库连接池中获取一个连接
}
}

1.4.10 c3p0-config.xml(连接池配置文件)
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/customer_system?useSSL=false</property>
<property name="user">root</property>
<property name="password">1234</property>
</default-config>

<!-- This app is massive! -->
<named-config name="intergalactoApp">
<property name="maxPoolSize">1000</property>
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>

</named-config>
</c3p0-config>


项目详细代码资源:

本人的github项目地址
https://github.com/Forever99/customer_system
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: