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

来源:互联网 发布:淘宝装修图片加热点 编辑:程序博客网 时间:2024/05/22 12:59

客户信息管理系统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;importcom.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;importcom.zhku.jsj144.zk.utils.TransactionUtils; public class CustomersService {          //解耦合技术    [反射技术+配置文件+接口]         //对比分析:         //以前代码耦合的时候:写代码是直接new对象,那么需要以来具体的类,如果没有这些具体的类,这         //么这个业务层默认的程序员就没有办法继续做开发         //现在,解耦合:引入了接口,通过接口去引用了返回的实现类,将来实现类有了之后,只需要将实现类集成进来,         //然后配置文件修改以下即可,不用再去修改源代码了。                 privateCustomersDaoCustomersDao=DaoFactory.getInstance().createDao(CustomersDao.class);//      privateCustomersDao CustomersDao=new CustomersDao();         publicint insert(Customers customers){//               CustomersDaoCustomersDao=new CustomersDao();                  //               CustomersDaoCustomersDao;//               try{//                         CustomersDao= (CustomersDao) DaoFactory.getDao();//解耦合技术获得//               }catch (Exception e) {//                         thrownew RuntimeException(e);//               }                   intcount = CustomersDao.insert(customers);                   returncount;         }          //查询所有用户信息         publicList selectAll() {                   ListresultList=CustomersDao.selectAll();//查询结果集                   returnresultList;         }          //删除一条记录,一个客户的信息         publicvoid deleteOne(String id) {                   CustomersDao.deleteOne(id);         } //      //批量删除//      publicvoid deleteAll(String[] choose) {//               //开启事务处理,循环进行删除,每次删除一条记录,如果删除失败,则进行回滚事务,否则,最后进行提交事务,并关闭资源//              //               //问题思考:Connection对象应该出现待在dao层,而不应该出现在service层,这样导致service层和到层耦合了//               //思考:如何进行解耦呢?//               //这样Service层就不会使用dao层才会使用的Connection对象了。//               //方法:ThreadLocal类[线程本地类]的使用,可以解决这个问题//              //              //               //开启事务,需要获得Connection对象//               Connectioncon=null;//               try{//                         con=JdbcUtils.getDatasourse().getConnection();//获得连接对象//                         con.setAutoCommit(false);//开启事务//                        //                         for(inti=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();//                         }//                         thrownew RuntimeException("批量删除失败");//               }//      }                 //完善后的deleteAll(String[]choose)方法         //批量删除         publicvoid deleteAll(String[] choose) {                   //开启事务处理,循环进行删除,每次删除一条记录,如果删除失败,则进行回滚事务,否则,最后进行提交事务,并关闭资源                    //确保同一个线程使用的始终是同一个Connection对象                   try{                            //开启事务                            TransactionUtils.startTransaction();                            //批量删除操作                            for(inti=0;i<choose.length;i++){                                     //手动管理事务,要自己传递Connection对象过去,确保Connection是唯一的                                     CustomersDao.deleteOneTransaction2(choose[i]);//每次删除一条记录                            }                            //提交事务                            TransactionUtils.commit();                   }catch(Exceptione){                            TransactionUtils.rollback();//回滚操作                            thrownew RuntimeException("批量删除失败...");                   }finally{                            //释放资源                            TransactionUtils.relase();                   }         }          publicCustomers getUpdateInfo(String id) {                   Customerscustomers=CustomersDao.getUpdateInfo(id);                   returncustomers;         }          publicvoid update(Customers customers) {                   CustomersDao.update(customers);         }          publicList selectCondition(String conditionName, String keyWords) {                   ListcustomersList=CustomersDao.selectCondition(conditionName,keyWords);                   returncustomersList;         }          //分页查询业务逻辑,目的获取分页pageBean的5个信息         //分页推导公式:         //1.  总页数=(总记录数+每页记录数-1)/每页记录数         //2.  初始索引=(当前页数-1)*每页记录数         publicPageBean pageQuery(String num) {                                     inttotalRecord=CustomersDao.selectAllCount();//总记录数                   intpageRecord=10;//每页记录数【默认是每页10条记录】                   inttotalPage=(totalRecord+pageRecord-1)/pageRecord;//总页数                   intcurrentPage=Integer.parseInt(num);//当前页数                                     //主要是初始索引参数,以及每页的记录数作为参数                   intstart=(currentPage-1)*pageRecord;//开始索引                   List<Customers>dataList=CustomersDao.selectPageList(start,pageRecord);//当前页记录数                                     //将pageBean的信息封装起来                   PageBeanpageBean=new PageBean();                   pageBean.setTotalPage(totalPage);                   pageBean.setTotalRecord(totalRecord);                   pageBean.setPageRecord(pageRecord);                   pageBean.setCurrentPage(currentPage);                   pageBean.setDataList(dataList);                                     returnpageBean;         }}


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 {          //插入用户信息         publicabstract int insert(Customers customers);          //查询用户信息         publicabstract List selectAll();          //删除一条记录         publicabstract void deleteOne(String id);          //删除一条记录,并手动管理事务         publicabstract void deleteOneTransaction(Connection con,String id);          //删除一条记录,并手动管理事务[写法2]         publicabstract void deleteOneTransaction2(String id);          //查询一条用户记录信息,用于修改使用         publicabstract Customers getUpdateInfo(String id);          //修改一条用户记录信息         publicabstract void update(Customers customers);          //条件查询         publicabstract List selectCondition(String conditionName, String keyWords);          //查找总记录个数         publicabstract int selectAllCount();          //分页查询         publicabstract 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; importorg.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;importorg.apache.commons.dbutils.handlers.BeanListHandler;importorg.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;importcom.zhku.jsj144.zk.utils.TransactionUtils; public class CustomersDaoImplementimplements CustomersDao {          //插入用户信息         /*(non-Javadoc)          * @seecom.zhku.jsj144.zk.dao.CustomersDao#insert(com.zhku.jsj144.zk.domain.Customers)          */         @Override         publicint insert(Customers customers){                   //调用工具类进行插入操作//               QueryRunnerqr=new QueryRunner();//没有获取连接                   try{                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                                     //id,用UUID工具进行生成                   Stringid=getId();                                     //参数数组                   Object[]params=new Object[]{id,customers.getName(),customers.getGender(),                                     customers.getBirthday(),customers.getEmail(),customers.getCellphone(),                                     customers.getPreference(),customers.getType(),customers.getDescription()};                                     intcount = qr.update("insert into customers values(?,?,?,?,?,?,?,?,?)",params);                   System.out.println("count:"+count);                   returncount;//返回插入结果                   }catch(SQLExceptione){                            thrownew RuntimeException(e);                   }                           }                 //生成并获取id         privateString getId(){                   Stringid=UUID.randomUUID().toString();                   id=id.replace("-","");                   returnid;         }          //查询用户信息         /*(non-Javadoc)          * @seecom.zhku.jsj144.zk.dao.CustomersDao#selectAll()          */         @Override         publicList selectAll() {                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   try{                            //返回查询结果集                            ListresultList = qr.query("select * from customers", newBeanListHandler(Customers.class));                            return  resultList;                   }catch (SQLException e) {                            thrownew RuntimeException(e);                   }         }          //删除一条记录         /*(non-Javadoc)          * @seecom.zhku.jsj144.zk.dao.CustomersDao#deleteOne(java.lang.String)          */         @Override         publicvoid deleteOne(String id) {                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   try{                            qr.update("deletefrom customers where id=?", id);                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }                           }          //删除一条记录,并手动管理事务         @Override         publicvoid deleteOneTransaction(Connection con,String id) {                   QueryRunnerqr=new QueryRunner();                   try{                            qr.update(con,"deletefrom customers where id=?", id);                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //删除一条记录,并手动管理事务[写法2]         @Override         publicvoid deleteOneTransaction2(String id) {                   QueryRunnerqr=new QueryRunner();                   try{                            //ThreadLocal类【线程本地类】的使用:确保同一个线程使用的始终是同一个Connection对象                            qr.update(TransactionUtils.getConnection(),"deletefrom customers where id=?", id);                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //查询一条用户记录信息,用于修改使用         @Override         publicCustomers getUpdateInfo(String id) {                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   Customerscustomers=null;                   try{                            customers= qr.query("select * from customers where id=?", newBeanHandler(Customers.class),id);                            returncustomers;                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //修改一条用户记录信息         @Override         publicvoid update(Customers customers) {                   QueryRunnerqr=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("updatecustomers set name=?,gender=?,birthday=?,cellphone=?,email=?,"                                               +"preference=?,type=?,description=? where id=?", params);                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //条件查询         @Override         publicList selectCondition(String conditionName, String keyWords) {                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   try{                            //select* from customers where name like '% 张 %'                            ListcustomersList=qr.query("select * from customers where"+conditionName+" like ?", new BeanListHandler(Customers.class),"%"+keyWords+"%");                            return  customersList;                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //查找总记录个数         @Override         publicint selectAllCount() {                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   try{//                         //异常:java.lang.ClassCastException:java.lang.Long cannot be cast to java.lang.Integer//                         intcount = (Integer) qr.query("select count(*) from customers", newScalarHandler());                                                       longcount = (Long) qr.query("select count(*) from customers", newScalarHandler());                            return(int)count;//此处再强制转换                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         }          //分页查询         //      物理分页         //      在sql查询时,从数据库只检索分页需要的数据         //      mysql物理分页,采用limit关键字         //      例如:检索11-20条 select *from user limit 10,10 ;         @Override         publicList<Customers> selectPageList(int start, int pageRecord) {                   //参数:初始索引,每页的记录数                   QueryRunnerqr=new QueryRunner(JdbcUtils.getDatasourse());                   try{                            //eg:select * from user limit 10,10 ;                            List<Customers>pageList = qr.query("select * from customers limit ?,?", newBeanListHandler(Customers.class),start,pageRecord);                            returnpageList;                   }catch (SQLException e) {                            thrownew RuntimeException(e);//抛出运行时异常                   }         } }


1.4.7 DaoFactory(dao层工厂)

packagecom.zhku.jsj144.zk.utils; importjava.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(){           ResourceBundlebundle=ResourceBundle.getBundle("dao");//读取dao.properties配置文件      //配置文件内容:CustomersDao=com.zhku.jsj144.zk.daoImpl.CustomersDaoImplement      //左边:接口  右边:接口的实现类      StringimplClass=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 {          privatestatic DataSource ds=new ComboPooledDataSource();//数据库连接池的数据源                 publicstatic DataSource getDatasourse(){                   returnds;//返回数据库连接池的数据源         }         publicConnection getConnection() throws SQLException{                   returnds.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>