Idea创建Maven多模块+Spring-boot jdbctemplate的使用

1、在打开Idea后选择Create New Project,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第1张图片

2、选择Maven,然后不要选Create from archetype,直接点击Next,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第2张图片

3、输入GroupId和ArtifactId,然后点击Next,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第3张图片

4、输入工程名称以及路径,然后点击Finish,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第4张图片

5、创建好之后如下图所示的目录结构:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第5张图片

6、右键单击src,然后在弹出的菜单中选择Delete,将其删除,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第6张图片

7、然后在项目名称上右键单击,依次选择New->Module,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第7张图片

8、然后选择Maven,直接单击Next,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第8张图片

9、然后只需要输入ArtifactId即可,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第9张图片

10、输入模块的名称,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第10张图片

11、如果出现Maven projects need to be imported,选择Enable Auto-Import表示自动导入,如下图所示:

12、在根项目中的pom.xml添加parent,然后所有的子模块都可以使用此parent中的jar,如添加:

 
        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
    

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第11张图片

13、在根项目中添加dependencies和dependency,所有子模块都可以使用此依赖,如:


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-actuator
            2.1.0.RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-test
            2.1.0.RELEASE
            test
        
    

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第12张图片

14、在mysql模块中的pom.xml添加连接mysql相应的jar包,如:


        
            org.springframework.boot
            spring-boot-starter-data-jpa
            2.1.0.RELEASE
        
        
            mysql
            mysql-connector-java
            8.0.13
        
    

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第13张图片

15、新建一个demo数据库,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第14张图片

16、创建一个tb_user表,如:

CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `age` int(11) NOT NULL COMMENT '年龄',
  `ctm` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第15张图片

17、插入相应的数据,如:

INSERT INTO `demo`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ;
INSERT INTO `demo`.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
INSERT INTO `demo`.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第16张图片

18、最后结果如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第17张图片

19、在mysql模块中创建相应的包,结构如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第18张图片

20、在resources创建一个application.yml文件,配置连接mysql的字符串(注意:每一项的冒号后都要有一个空格,否则会出错),如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第19张图片

21、在bean中创建一个User类,此类对应数据库表tb_user,并且每个变量对应一个字段,如:

package com.win.mysql.bean;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private int age;
    private Date ctm;
    public User() {
    }
    public User(String username, int age) {
        this.username = username;
        this.age = age;
        this.ctm = new Date();
    }
    public void setUsername(String username){
        this.username=username;
    }
    public void setAge(int age){
        this.age=age;
    }
    public void setCtm(Date ctm){
        this.ctm=ctm;
    }
    public int getId(){
        return this.id;
    }
    public String getUsername(){
        return this.username;
    }
    public int getAge(){
        return this.age;
    }
    public Date getCtm(){
        return this.ctm;
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第20张图片

22、创建一个UserDao接口,如:

package com.win.mysql.dao;

import com.win.mysql.bean.User;

import java.util.List;

public interface UserDao {
    public User getUserById(Integer id);
    public List getUserList();
    public int add(User user);
    public int update(Integer id, User user);
    public int delete(Integer id);
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第21张图片

23、在dao包中创建一个impl包,并创建一个UserDaoImpl类用来实现UserDao接口,此类中有JdbcTemplate,Spring-boot会自动读取配置文件中的信息到JdbcTemplate中,然后通过JdbcTemplate就可以进行RCUD了,如:

package com.win.mysql.dao.impl;

import com.win.mysql.bean.User;
import com.win.mysql.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public User getUserById(Integer id){
        List list = jdbcTemplate.query("select * from tb_user where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }
    @Override
    public List getUserList(){
        List list = jdbcTemplate.query("select * from tb_user", new Object[]{}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            return list;
        }else{
            return null;
        }
    }
    @Override
    public int add(User user){
        return jdbcTemplate.update("insert into tb_user(username, age, ctm) values(?, ?, ?)",
                user.getUsername(),user.getAge(), new Date());
    }
    @Override
    public int update(Integer id, User user){
        return jdbcTemplate.update("UPDATE tb_user SET username = ? , age = ? WHERE id=?",
                user.getUsername(),user.getAge(), id);
    }
    @Override
    public int delete(Integer id){
        return jdbcTemplate.update("DELETE from tb_user where id = ? ",id);
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第22张图片

24、在service包中创建一个UserService接口,如:

package com.win.mysql.service;

import com.win.mysql.bean.User;
import java.util.List;
public interface UserService {
    public User getUserById(Integer id);
    public List getUserList();
    public int add(User user);
    public int update(Integer id, User user);
    public int delete(Integer id);
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第23张图片

25、在service包中创建一个impl包,并创建一个UserServiceImpl类用来实现UserService接口,如:

package com.win.mysql.service.impl;

import com.win.mysql.bean.User;
import com.win.mysql.dao.UserDao;
import com.win.mysql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User getUserById(Integer id){
        return userDao.getUserById(id);
    }
    @Override
    public List getUserList(){
        return userDao.getUserList();
    }
    @Override
    public int add(User user){
        return userDao.add(user);
    }
    @Override
    public int update(Integer id, User user){
        return userDao.update(id, user);
    }
    @Override
    public int delete(Integer id){
        return userDao.delete(id);
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第24张图片

26、在bean包中创建一个JsonResult类,如:

package com.win.mysql.bean;

public class JsonResult {
    private String status = null;
    private Object result = null;
    public JsonResult status(String status) {
        this.status = status;
        return this;
    }
    public void setResult(Object user){
        this.result=user;
    }
    public Object getResult(){
        return this.result;
    }
    public void setStatus(String status){
        this.status=status;
    }
    public String getStatus(){
        return this.status;
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第25张图片

27、在web包中创建一个控制类UserController,通过http请求的都在此类中,如:

package com.win.mysql.web;

import com.win.mysql.bean.JsonResult;
import com.win.mysql.bean.User;
import com.win.mysql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public ResponseEntity getUserById (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = userService.getUserById(id);
            r.setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 查询用户列表
     * @return
     */
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity getUserList (){
        JsonResult r = new JsonResult();
        try {
            List users = userService.getUserList();
            r.setResult(users);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity add (@RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            int orderId = userService.add(user);
            if (orderId < 0) {
                r.setResult(orderId);
                r.setStatus("fail");
            } else {
                r.setResult(orderId);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            int ret = userService.delete(id);
            if (ret < 0) {
                r.setResult(ret);
                r.setStatus("fail");
            } else {
                r.setResult(ret);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 根据id修改用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public ResponseEntity update (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            int ret = userService.update(id, user);
            if (ret < 0) {
                r.setResult(ret);
                r.setStatus("fail");
            } else {
                r.setResult(ret);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第26张图片

28、在mysql包中创建一个spring-boot的启动类Application,如:

package com.win.mysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableAutoConfiguration
@SpringBootApplication
public class Application {
    public static void main( String[] args )
    {
        System.out.println( "start....." );
        SpringApplication.run(Application.class, args);
    }
}

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第27张图片

29、在启动后出现错误,如:

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.
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) [HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) [HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115) [HikariCP-3.2.0.jar:na]
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.2.0.jar:na]
	at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151) [spring-jdbc-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) [spring-jdbc-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) [spring-jdbc-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319) [spring-jdbc-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356) [spring-jdbc-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:142) [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:112) [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$94d70ee3.CGLIB$jpaVendorAdapter$4() [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$94d70ee3$$FastClassBySpringCGLIB$$c0920c0.invoke() [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) [spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) [spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$94d70ee3.jpaVendorAdapter() [spring-boot-autoconfigure-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:620) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:455) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:508) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:508) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:853) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
	at com.win.mysql.Application.main(Application.java:13) ~[classes/:na]
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: 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.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_181]
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_181]
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_181]
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_181]
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ~[mysql-connector-java-8.0.13.jar:8.0.13]

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第28张图片

30、出现此错误说明在连接mysql时的时区不对,只需要在连接串后加上?serverTimezone=UTC即可,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第29张图片

31、再次启动即可启动成功,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第30张图片

32、在浏览器中输入:http://127.0.0.1:8080/users即可输入结果,如下图所示:

33、在输出结果可以看到其中的id全部是0,这是由于在User类中缺少setId方法,只需要添加即可,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第31张图片

34、在此刷新即可正常输入,如下图所示:

35、在浏览器中输入:http://127.0.0.1:8080/user/1即可查询指定用户,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第32张图片

36、使用火狐浏览器中的RESTClient插件进行测试添加用户,选择post请求,然后输入:http://127.0.0.1:8080/user,然后添加HTTP头,输入正文,点击发送即可添加,并且有返回状态,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第33张图片

37、在此查询所有用户即可显示,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第34张图片

38、修改用户信息,选择put请求,然后输入:http://127.0.0.1:8080/user/1,输入要修改的内容,表示修改指定ID的信息,点击发送即可修改,并且有返回状态,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第35张图片

39、在此刷新可以看到已经更新了,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第36张图片

40、删除用户信息,选择DELETE请求,然后输入:http://127.0.0.1:8080/user/1,不需要输入内容,点击发送即可删除,并且有返回状态,如下图所示:

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第37张图片

41、再次刷新显示ID为1的已经被删除,如下图所示:

 

Idea创建Maven多模块+Spring-boot jdbctemplate的使用_第38张图片

总结:

(1)在程序启动时,在Application.java类中有一个@SpringBootApplication注解,它包含了@Configuration + @EnableAutoConfiguration + @ComponentScan三个注解,说明在启动时会自动获取配置(比如配置的数据库连接参数等)

(2)然后在去运行main,进而运行SpringApplication.run(Application.class, args);然后开始进行初始化Spring相关的信息,比如其他类的注解。

(3)当从浏览器中输入网址时,spring就会去找被@RestController的相应的类,然后进行路径解析,然后@RequestMapping来注释具体调用的是那个路径下的方法,如:@RequestMapping(value = "users", method = RequestMethod.GET),根路径为:http://127.0.0.1:8080,如果加上value,那么就会自动匹配成http://127.0.0.1:8080/users,然后在进一步判断http请求的方法,如果为:RequestMethod.GET,则会调用getUserList ();

(4)在getUserList ()方法中会有一个userService.getUserList(),此处的userService通过@Service已经实例化为了UserServiceImpl类,那么此时调用的userService.getUserList()就会调用UserServiceImpl类中的getUserList()。

(5)在UserServiceImpl类中的getUserList()方法中会调用userDao.getUserList()方法,而userDao通过@Repository已经实例化为了UserDaoImpl类,那么此时调用的userDao.getUserList()就会调用UserDaoImpl类中的getUserList()方法。

(6)在UserDaoImpl类中的getUserList()方法中通过jdbcTemplate.query("select * from tb_user", new Object[]{}, new BeanPropertyRowMapper(User.class)),对数据表进行查询,而jdbcTemplate则是在spring-boot启动时会自动配置数据库的相关连接,直接可以使用。

(7)把查询结果生成一个List,然后返回到UserController中,并构造一个JsonResult对象,然后通过ResponseEntity对象构造成一个json格式对象,然后返回到浏览器中。

 

你可能感兴趣的:(Idea创建Maven多模块+Spring-boot jdbctemplate的使用)