springboot学习之路:Druid+Mybatis操作数据

2019-06-26  本文已影响0人  Liopisces

初学SpringBoot,想着着手搭建一个后台管理系统,来实践一下所学框架。

1. 导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

由于数据库使用的是mysql,故而同时引入mysql-connector-java依赖。Maven真乃神器也!
如果有想要引入的依赖,却不知道依赖地址的话,可以去maven repository中查找。

2. 配置application.yml文件

application.yml是系统各个组件的参数设置文件,可以在此定义全局参数。在此,我将配置数据库链接的相关参数、druid的各项基础参数:

spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/test001
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  configuration:
    map-underscore-to-camel-case: true

用户可以根据自己的实际情况修改相关参数。在此处,着重强调一下配置Mybatis中的驼峰命名法,即Database中的命名均为小写加下划线,而java中的命名规则一般是小写加大写字母,例如:数据库中字段student_name,而在java中则是studentName,这样引起的不一致,在后来返回的JSON数据中将引发错误,而不予返回。此处注明开启驼峰命名法,则可以避免这样的错误。

3. 配置DruidConfig

在config目录下新建DruidConfig.java文件,用以配置Druid的网页访问以及拦截。

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
//        initParams.put("allow","");//默认就是允许所有访问
//        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

配置完这些之后就可以通过浏览器查看数据库状态了,是一个非常便捷的方式!

4. 配置实体类

实体类的字段必须与数据库表中的字段完全一致(驼峰命名,在之前已经介绍了),并赋予get&set方法。目的在于将数据的操作完全对象化。此处仅以StudentMath类为代表。
养成习惯,将所有的实体类均放在同一个文件夹下,此处为model文件夹,文件结构如下:

2.png
public class StudentMathDomain {
    private Integer id;
    private String school;
    private Integer sex;
    private Integer age;
    private String address;
    private String famsize;
    private String Pstatus;
    private Integer Medu;
    private Integer Fedu;
    private String Mjob;
    private String Fjob;

    @Override
    public String toString() {
        return "StudentMathDomain{" +
                "id=" + id +
                ", school='" + school + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", famsize='" + famsize + '\'' +
                ", Pstatus='" + Pstatus + '\'' +
                ", Medu=" + Medu +
                ", Fedu=" + Fedu +
                ", Mjob='" + Mjob + '\'' +
                ", Fjob='" + Fjob + '\'' +
                '}';
    }
              /**
                GET&SET方法省略。    
              **/

 }

5. 编写DAO接口

DAO(Data Access Object)层,定义了所有的数据库访问操作。而且应当是数据库访问的唯一路径。
使用注解版的Mybatis使得DAO操作更加的浅显易懂,不用去关联xml文件。DAO目录结构如下:

3.png
@Mapper
public interface StudentMathDao {

    @Select("select * from StudentMat")
    public List<StudentMathDomain> getStudentMathAll();

    @Select("select * from StudentMat where id =#{id}")
    public StudentMathDomain getStudentMathById(Integer id);
}

看到这里,是不是觉得注解版的MyBatis非常的便捷~

6. 编写Service服务

刚开始的时候确实觉得很奇怪,明明DAO接口已经完成了数据库操作,已经达到了预期的目的了,为什么还要加上一个如此多余的Service服务呢?
确实,DAO操作已经完成了我们的数据库操作,而Service服务的存在就是为了解耦合。
理论上,在程序设计的时候,DAO层负责最底层的数据操作,Service层负责向对象提供服务,两者所在层次不同,所以需要进行分离。
实际上,简单的查库操作并不能完全满足多种多样的用户需求,通过Service层的再次封装,将取得更多样化的服务。相当于一个Service并不仅仅只是面向一个DAO。
举个简单的例子,分页操作,如果只是单纯的DAO的话,几乎无法实现。而引入了Service进一步封装的概念之后,将查询到的原始数据再次封装到PageInfo类中,方便了用户操作。
Service层分为名称方法和实现方法,其结构图如下:


4.png
public interface StudentMathService {

     PageInfo<StudentMathDomain> getStudentMathAll(int pageNum , int pageSize);

     StudentMathDomain getStudentMathById(Integer id);
}
@Service
public class StudentMathServiceImpl implements StudentMathService {

    @Autowired
    StudentMathDao studentMathDao;


    @Override
    public PageInfo<StudentMathDomain> getStudentMathAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<StudentMathDomain> studentinfo = studentMathDao.getStudentMathAll();
        PageInfo<StudentMathDomain> pageInfo = new PageInfo<>(studentinfo);
        return pageInfo;
    }

    @Override
    public StudentMathDomain getStudentMathById(Integer id) {
        return studentMathDao.getStudentMathById(id);
    }
}

接口定义名称,Impl类定义具体实现方法。
在ServiceImpl类中:

上一篇 下一篇

猜你喜欢

热点阅读