从零开始写后台(一)

心路历程

工作三年,说转Java后台就已经说了一年半,中间虽然说已经把大致的SSM(SpringMVC-Spring-MyBatis)框架和Spring Boot-MyBatis框架学了一遍,但是苦于没有实践机会,中间又再次投入Android的深入学习中,已经把后台的东西忘了个七七八八,现在趁着这次写项目的机会,逐步拾起来。

准备

本次项目的需求很简单,就是搭建起一套框架,实现一存一取两个接口,并连接数据库。经过分析,考虑还是使用Spring Boot+MyBatis框架。问我怎么考虑的?搭建简单呗(:з」∠)。顺带说一句,因为习惯了Android Studio,所以对Java后台的开发,选用IntelliJ IDEA作为开发工具,版本为Ultimate 2018.1。

Spring Boot搭建

一、搭建Java环境

现在网上已经很多此类内容,这里就不再赘述了。

二、创建项目

1.打开IDEA -> Create New Project创建新项目。


打开IDEA创建新项目

2.在左侧标签栏中选择Spring Initializr,Project SDK选择java 1.8,Service URL使用默认的就好,直接点Next。


New Project 1

3.按照自己的情况填写Group和Artifact等信息,填完之后Next。
New Project 2

4.选择右侧标签栏中的Web标签,并勾选中间的Web选项,再选择右侧SQL标签,勾选中间JPA、MySQL、MyBatis选项,Next。


New Project 3

5.最后一页可以填写Project name和设置Project location,More Settings默认就好,Finish。
New Project 4

Spring Boot项目到这里就创建完毕了,以下是项目的初始目录结构。
目录结构

其中pom.xml中已经集成了Spring Boot的各种jar包,并包含了连接MySql需要的包。
Spring Boot内置了tomcat,所以,可以直接运行FacerecApplication中的main方法启动项目,不需要额外配置tomcat。

三、启动项目

让我们启动项目测试一下。


run 日志

Oh,no!拜托,给个面子,怎么就报错了,让我们来看看是什么问题。

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-03-28 11:12:54.985 ERROR 516896 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

戳了一下度娘,找到了问题的原因。

原因:
  spring boot默认会加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration类,DataSourceAutoConfiguration类使用了@Configuration注解向spring注入了dataSource bean。因为工程中没有关于dataSource相关的配置信息,当spring创建dataSource bean因缺少相关的信息就会报错。
解决方法:

在Application类上增加@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) ,
或者配置dataSource。

作者:格物知行
来源:CSDN
原文:https://blog.csdn.net/u012562117/article/details/79935224
版权声明:本文为博主原创文章,转载请附上博文链接!

原来是项目刚刚创建,还没有创建数据源!后面我们要操作数据库,所以我们就来着手配置数据源。

首先,在src/main/java/[package name]下新建目录entity,并在此目录下新增一个Pojo类。

package com.***.facerec.entity;

public class DevMapRec {

    private String recServer;

    private String deviceId;

    public String getRecServer() {
        return recServer;
    }

    public void setRecServer(String recServer) {
        this.recServer = recServer;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
}

接下来,在src/main/java/[package name]下新建目录controller,并新建一个Controller。

package com.***.facerec.controller;

import com.***.facerec.entity.DevMapRec;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/device")
public class DevMapRecController {

    @RequestMapping("getDevMapRec")
    public DevMapRec getDevMapRec() {
        DevMapRec map = new DevMapRec();
        map.setDeviceId("device");
        map.setRecServer("127.0.0.1");
        return map;
    }

}

在Spring Boot启动FacerecApplication时,会在Application当前所在的包或其子包中扫描所有相关注解的类。
最后,我们再在resources下的application.properties文件里加入配置。

#数据库配置
spring.profiles.active=dev
spring.datasource.url=jdbc:mysql://localhost:3306/facerec
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

个人比较偏好使用yml格式的application.yml。

#公共配置与profiles选择无关
#数据库配置
spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

如此目录结构就变成了下面的样子。


新目录结构

接下来,在在本地连接中新建一个facerec库,个人习惯使用Navicat来管理数据库。


新建数据库

搞定,让我们再run一次。
run日志 2

这又是什么鬼?

java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

乍一看是说数据库的时区设置有问题,不太清楚,再戳戳度娘吧。

错误原因:Mysql和本地时区不同所导致的。
这问题也是再使用了Mysql 8.0+ 的版本才出现的
只需要修改一下配置文件即可

根据这篇文章,我们把application.yml改成了这样

#数据源配置
spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

好了好了,再跑一次_(:з」∠)_。

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-03-28 14:30:54.015  INFO 529200 --- [           main] com.***.facerec.FacerecApplication    : Starting FacerecApplication on DESKTOP-HFD4L3T with PID 529200 (D:\Code\JavaWorkSpace\facerec\target\classes started by Lilin in D:\Code\JavaWorkSpace\facerec)
2019-03-28 14:30:54.018  INFO 529200 --- [           main] com.***.facerec.FacerecApplication    : The following profiles are active: dev
2019-03-28 14:30:54.727  WARN 529200 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.***.facerec.controller, com.***.facerec]' package. Please check your configuration.
2019-03-28 14:30:54.762  INFO 529200 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-03-28 14:30:54.775  INFO 529200 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 7ms. Found 0 repository interfaces.
2019-03-28 14:30:55.037  INFO 529200 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8e473666] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-03-28 14:30:55.364  INFO 529200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-03-28 14:30:55.391  INFO 529200 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-03-28 14:30:55.391  INFO 529200 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-03-28 14:30:55.398  INFO 529200 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:\Tools\SecureCRT\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.8.0_144\bin;C:\ProgramData\chocolatey\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\OpenSSH-Win64;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Lilin\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\Lilin\AppData\Local\Programs\Python\Python36-32\;C:\Users\Lilin\AppData\Local\Microsoft\WindowsApps;D:\Tools\Android\sdk\platform-tools;";C:\Program Files\Java\jdk1.8.0_144\bin;C:\Program Files\Java\jdk1.8.0_144\jre\bin";C:\Users\Lilin\AppData\Roaming\npm;D:\Tools\Microsoft VS Code\bin;C:\Program Files\MySQL\MySQL Server 5.7\bin;D:\Tools\apache-maven-3.5.3\bin;D:\Tools\Android\sdk\ndk-bundle;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\Lilin\AppData\Local\Programs\Fiddler;C:\Users\Lilin\AppData\Local\Microsoft\WindowsApps;D:\Tools\flutter\bin;;.]
2019-03-28 14:30:55.541  INFO 529200 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-03-28 14:30:55.541  INFO 529200 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1463 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-03-28 14:30:55.718  INFO 529200 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-03-28 14:30:55.719  WARN 529200 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-03-28 14:30:55.851  INFO 529200 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-03-28 14:30:55.905  INFO 529200 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-03-28 14:30:56.019  INFO 529200 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-03-28 14:30:56.020  INFO 529200 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-03-28 14:30:56.140  INFO 529200 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-03-28 14:30:56.258  INFO 529200 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-03-28 14:30:56.401  INFO 529200 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-03-28 14:30:56.559  INFO 529200 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-03-28 14:30:56.589  WARN 529200 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-03-28 14:30:56.805  INFO 529200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-03-28 14:30:56.808  INFO 529200 --- [           main] com.***.facerec.FacerecApplication    : Started FacerecApplication in 3.416 seconds (JVM running for 4.607)

哈哈,大功告成。
让我们在浏览器上输入http://localhost:8080/device/getDevMapRec测试一下。

请求结果

excellent,成功返回了数据。

四、集成MyBatis

1.集成阿里粑粑的druid连接池,戳这里看具体连接池的意义。在pom.xml的dependencies标签中加入


    com.alibaba
    druid
    1.1.0

2.在application.yml中配置druid数据源

#数据源配置
spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://localhost:3306/facerec?serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    #druid数据源
    type: com.alibaba.druid.pool.DruidDataSource

3.在数据库中建表,并使用mybatis-generator自动生成或者手动创建Mapper接口以及编写Mapper.xml。

以下是我用mybatis-generator自动生成的Mapper接口

package com.***.facerec.mapper;

import com.***.facerec.entity.DevMapRec;
import java.util.List;

public interface DevMapRecMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_wk_devmaprec
     *
     * @mbggenerated Thu Mar 28 18:41:04 CST 2019
     */
    int insert(DevMapRec record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_wk_devmaprec
     *
     * @mbggenerated Thu Mar 28 18:41:04 CST 2019
     */
    List selectAll();
}

以下是Mapper.xml




  
    
    
    
    
  
  
    
    insert into t_wk_devmaprec (id, deviceId, recServer
      )
    values (#{id,jdbcType=INTEGER}, #{deviceid,jdbcType=VARCHAR}, #{recserver,jdbcType=CHAR}
      )
  
  

接下来,编写Service以及修改Controller

package com.***.facerec.service;

import com.***.facerec.entity.DevMapRec;

import java.util.List;

/**
 * Service接口
 */
public interface DevMapRecService {

    List selectAll();

    int insert(DevMapRec devMapRec);
}

Service实现

package com.***.facerec.service;

import com.***.facerec.entity.DevMapRec;
import com.***.facerec.mapper.DevMapRecMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("dmrService")
@MapperScan(basePackages = "com.***.facerec.mapper")//这里要特别注意
public class DevMapRecServiceImpl implements DevMapRecService {

    @Resource
    private DevMapRecMapper mapper;

    @Override
    public List selectAll() {
        return mapper.selectAll();
    }

    @Override
    public int insert(DevMapRec devMapRec) {
        return mapper.insert(devMapRec);
    }
}

最后是Controller

package com.***.facerec.controller;

import com.***.facerec.entity.DevMapRec;
import com.***.facerec.service.DevMapRecService;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@EnableAutoConfiguration
@RequestMapping("/device")
public class DevMapRecController {

    @Resource
    private DevMapRecService service;

    @RequestMapping("getDevMapRec")
    public List getDevMapRec() {
        return service.selectAll();
    }

}

终于搞定了,接下来我们在数据库中随便插入几条数据,然后请求查看结果。


请求结果

最后,在看看现在的目录结构


目录结构

总结

这是算是重新复习了一遍Spring Boot+MyBatis的搭建,磕磕绊绊,终于还是完成了。这也是我第一篇比较长的博文,也是磕磕绊绊,不过的确是能让我注意到闷头做事时不会注意到的东西,还要继续努力才行!

你可能感兴趣的:(从零开始写后台(一))