最近也是比较忙,也只能忙里偷闲地抓紧时间接着学习一下技术,自从上次学习了maven之后,越来越对框架产生了兴趣,下了好多的spring视屏,听着老师的建议,最近也萌生了看别人的代码进行学习的想法,然后就上了知乎搜了搜优秀的java框架,发现了一个比较感兴趣的,符合最近在学习的方面的项目。


上地址:https://github.com/C0de8ug/Javaee-tutorial
感谢C0de8ug上传的项目,帮助了许许多多像我们这样走在框架学习路上的新人们。

不多说,开始主题


  • 访问数据库的传统方法
    传统访问数据库的方法非常面向过程,分为以下几步
    – 实例化connection
    – 实例化statement
    – 通过statement的参数sql语句访问数据库,返回数据进行处理
代码:
import java.sql.Statement;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;public class DBAccess {public static void main(String[] args) throws SQLException, FileNotFoundException, IOException{DBAccess access = new DBAccess();access.test();}private void test() throws SQLException, FileNotFoundException, IOException{String url = "jdbc:postgresql://localhost:5432/rylynn"; Properties p = new Properties();p.load(new FileInputStream("reg.txt"));Connection connection = DriverManager.getConnection(url,p);       //建立connectionStatement statement = connection.createStatement();       //建立satatementstatement.execute("insert into abo values((001),'hnb')");       //执行sql语句ResultSet resultSet = statement.executeQuery("select number from abo where number < 2");while(resultSet.next()){int id = resultSet.getInt(1);//      String name = resultSet.getString(1);System.out.println("ID:" + id);}statement.close();connection.close();}
}       

传统数据库访问模式缺点显而易见:
一就是各个模块间的耦合太紧,statement要依赖connection,connection还依赖于数据库的种类。
二就是如果我改变的数据库的种类,或者要提供不同的数据库服务,那么我就要提供大量的重复代码。


面向抽象的编程思想告诉我们要面向接口编程,这种编程模式的好处就是,各个模块之间分工明确,而且互不干扰,首先介绍一下各个层次之间分工。

  • dao层:dao层叫数据访问层,全称为data access object,属于一种比较底层,比较基础的操作,具体到对于某个表、某个实体的增删改查
  • service层:service层叫服务层,被称为服务,肯定是相比之下比较高层次的一层结构,相当于将几种操作封装起来,至于为什么service层要使用接口来定义有以下几点好处:
    • 在java中接口是多继承的,而类是单继承的,如果你需要一个类实现多个service,你用接口可以实现,用类定义service就没那么灵活
    • 要提供不同的数据库的服务时,我们只需要面对接口用不同的类实现即可,而不用重复地定义类
    • 编程规范问题,接口化的编程为的就是将实现封装起来,然调用者只关心接口不关心实现,也就是“高内聚,低耦合”的思想。
  • service实现类:也顾名思义,service实现类实现了service接口,进行具体的业务操作。

这里用C0de8ug公开在github上面的项目的代码来说明

dao层、service层以及service实现类的结构:

项目中使用了mybatis框架进行数据库的操作
以对于user的操作为例进行说明:
userdao:

public interface UserDao {public List<User> findAll();public User findById(String id);public void update(User user);public void add(User user);public void delete(String id);public User findByIdAndPassword(@Param("id") String username, @Param("password") String password);public void updatePassword(@Param("userId") String id, @Param("password") String password);User findByUsername(String username);}

在接口中对方法进行了定义,在UserDao.xml中给出了sql语句实现
在UserDao中,就对user这个实体的增删补查各类基本的操作进行了声明,并用mybatis框架进行实现。

下面给出部分UserDao.xml的代码

<select id="findAll" resultMap="user_map">SELECT * FROM user WHERE user_id != 'admin'</select><select id="findById" parameterType="String" resultMap="user_map">SELECT * FROM user WHERE user_id = #{value}</select><update id="update" parameterType="User">UPDATE user SET password = #{password} ,authority = #{authority} WHERE user_id = #{userId}</update><update id="updatePassword" parameterType="map">UPDATE user SET password = #{password} WHERE user_id = #{userId}</update><insert id="add" parameterType="User">INSERT INTO user(user_id,password,salt,role_ids,locked) VALUES(#{userId},#{password},#{salt},#{roleIdsStr},#{locked})</insert><select id="findByIdAndPassword" parameterType="map" resultMap="user_map">SELECT * FROM user WHERE user_id = #{id} AND password = #{password}</select>

下面来看看service层的代码

import com.giit.www.entity.User;
import com.giit.www.entity.custom.UserVo;import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;/*** Created by c0de8ug on 16-2-9.*/
public interface UserBiz {public List<UserVo> findAll() throws InvocationTargetException, IllegalAccessException;public User findById(String id);public void update(User user);public void add(User user);public void delete(String id);public void changePassword(String userId, String newPassword);public User findByUsername(String username);public Set<String> findRoles(String username);public Set<String> findPermissions(String username);
}

显然,service层里面的方法相较于dao层中的方法进行了一层包装,例如通过id查找用户,通过用户名查找用户,是在基础的操作上又增加了一层包装的,实现的是相对高级的操作。最后将这些操作在serviceimpl类中实现,代码比较多,这里还是只给出了部分代码,

import com.giit.www.college.dao.StaffDao;
import com.giit.www.entity.Role;
import com.giit.www.entity.Staff;
import com.giit.www.entity.User;
import com.giit.www.entity.custom.UserVo;
import com.giit.www.system.dao.RoleDao;
import com.giit.www.system.dao.UserDao;
import com.giit.www.system.service.RoleBiz;
import com.giit.www.system.service.UserBiz;
import com.giit.www.util.PasswordHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;/*** Created by c0de8ug on 16-2-9.*/@Service
public class UserBizImpl implements UserBiz {@ResourceUserDao userDao;@ResourceRoleDao roleDao;@ResourceStaffDao staffDao;@Resourceprivate PasswordHelper passwordHelper;@Resource(name = "roleBizImpl")private RoleBiz roleBiz;@Overridepublic List<UserVo> findAll() throws InvocationTargetException, IllegalAccessException {List<UserVo> userVoList = new ArrayList<>();List userList = userDao.findAll();Iterator iterator = userList.iterator();while (iterator.hasNext()) {StringBuilder s = new StringBuilder();User user = (User) iterator.next();List<Long> roleIds = user.getRoleIds();UserVo userVo = new UserVo();BeanUtils.copyProperties(userVo, user);if (roleIds != null) {int i = 0;int size = roleIds.size();for (; i < size - 1; i++) {Role role = roleDao.findOne(roleIds.get(i));s.append(role.getDescription());s.append(",");}Role role = roleDao.findOne(roleIds.get(i));s.append(role.getDescription());userVo.setRoleIdsStr(s.toString());}userVoList.add(userVo);}return userVoList;}

由此看到,这样进行分层,访问数据库和进行service之间的分工明确,如果我需要对service的需求修改,无需改变dao层的代码,只要在实现上改变即可,如果我有访问数据库的新需求,那我也只要在dao层的代码中增添即可。

框架学习(1)——service层,dao层和service实现类进行数据库操作相关推荐

  1. 为什么要用impl继承service层_JavaWeb service层 dao层 采用接口+impl 的原因

    service层 采用接口+impl : 是为了应对可能不同情形下,会存在多套业务逻辑.在调用的时候,根据实际情况去调用对应的serviceImpl eg: 存在 serviceImp1, servi ...

  2. python学习第6天---django框架---模型类及数据库操作

    python学习第6天---django框架---模型类及数据库操作 目录 文章目录 1.字段与选项 2.查询函数 3.查询集 4.模型类之间的关系 4.1.对应关系 4.2.关联查询 5.模型管理器 ...

  3. vo、dto、bo、do、po的概念理解以及与controller、service、dao层的对应关系

    目录 概念 关于do的理解 业务逻辑分层 基于springboot的逻辑分层结构 什么时候需要定义这么多O 实际项目中的使用方式 同一微服务中 不同微服务 一般起名规则 概念 VO(View Obje ...

  4. 表现层 业务层 持久层 web层 service层 dao层的相关概念描述

    我们的架构一般分为两种, 一种是C/S(客户端/服务器),另一种是B/S(浏览器/服务器). 在我接下来学习的SpringMVC种,几乎都是B/S架构开发的. 其标准的三层架构中,一般分为:表现层,业 ...

  5. php 服务层dao层,DAO层,Service层,Controller层、View层详解

    1.Dao层 Dao层主要是做数据持久层的工作,负责与数据库进行联络的一些任务都封装在此,Dao层的设计首先是设计Dao的接口,然后在Spring的配置文件中定义此接口的实现类,然后就可在模块中调用此 ...

  6. dao层(dao层的作用)

    DAO定义了什么呢? 它定义数据库的结构,数据库中对象的名称及这些对象的属性 JAVA的DAO是什么呢? DAO是Data Access Object数据访问接口,数据访问:故名思义就是与数据库打交道 ...

  7. Service和DAO层方法命名讲究

    Dao 接口命名 insert batchInsert selectOne selectById count selectList update deleteById Service 接口命名 add ...

  8. Spring框架学习笔记04:初探Spring——采用Java配置类管理Bean

    文章目录 一.课程引入 二.采用Java配置类管理Bean (一)打开项目[SpringDemo2021] (二)创建net.hw.spring.lesson04包 (三)创建杀龙任务类 (四)创建勇 ...

  9. Spring框架学习笔记03:初探Spring——利用注解配置类取代Spring配置文件

    文章目录 一.课程引入 二.利用注解配置类取代Spring配置文件 (一)打开项目[SpringDemo2021] (二)创建net.hw.spring.lesson03包 (三)移植上一讲的接口和类 ...

最新文章

  1. CVPR2017-最新目标检测相关
  2. Spring简单总结
  3. 初学者的困惑:OOP与一般编程的区别
  4. mybatis学习2之ResultMap结果集映射
  5. 计算机浮点数运算误差与解决误差的算法
  6. leetcode98. 验证二叉搜索树
  7. 30分钟了解C 11新特性
  8. linux 运行jupyter,在 Linux 上安装并运行 Jupyter
  9. github高级搜索技巧_百度搜索引擎高级使用技巧
  10. “杀死” APP 的留白设计!
  11. 品尝阿里云容器服务:食用注意事项
  12. opencv python 高斯滤波_Python OpenCV实验(3):实现图像的高斯滤波处理
  13. php 到处excel 乱码,php 导出excel乱码怎么办
  14. 高程(DEM) ASCII数据获取
  15. 安装oracle18c前要求,oracle18c安装
  16. 闪电分镜 一款影视前期策划的完美解决方案
  17. 停车收费PDA手持终端
  18. 特殊注释标记todo的有关信息
  19. 软件 ce ee 含义和区别
  20. Java标准简历制作

热门文章

  1. latex排版原理 常用算法排版伪代码模块 添加注释以及注意事项
  2. piblic class 和class的区别
  3. mysql sql 除法运算_SQL语句怎么表示除法运算?
  4. RGB图灰度及通道理解
  5. kafka sparksteaming
  6. IIS 请求报503
  7. props的几种写法
  8. 无需第三方软件,在 Yosemite 下给 iOS 设备轻松录屏
  9. 第三章 关系数据模型
  10. 服务器常用语言,计算机常用词汇--语言及服务器篇