Springboot连MySql demo

今天把工程调出来,发现又有问题:

1. 之前一直可以运行,今天突然报错:

Request method 'GET' not supported

@PostMapping要改成@RequestMapping("/input") 

2. springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

https://blog.csdn.net/IBLiplus/article/details/86491530

3. create connection SQLException, url: jdbc:mysql://localhost:3306/mydb, errorCode 0, state 01S00

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. 

将spring.datasource.url后加入?serverTimezone=UTC即可解决

  C:\work\code\hello\config\database.properties 
  C:\work\code\hello\src\main\resources\database.properties 
 

4.### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: Column 'name' specified twice

### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: Column 'name' specified twice

@Table(name="t_user")
public class UserEntity {


    @Column(name = "name") //删去这行, 重复定义
    private String id;

    private String name;

    private  String data;

}

运行了一下,能把数据配进表格了:

5.想要整理代码时,发现总会有

Error:(8, 25) java: 程序包javax.persistence不存在,maven reimport一下就好

https://blog.csdn.net/Luojun13Class/article/details/81483151 

 

至此,我的第一个JAVA项目(Springboot + Mysql)写好啦~

陆陆续续花了挺久了,不过终于是把基本的后端服务+写到数据库搞了一把~

接下来要搞怎么操作数据库啦 撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。

HelloController

package com.jiayuezh.hello.controller;



import com.jiayuezh.hello.dto.UserDto;
import com.jiayuezh.hello.dto.ResponseDto;

import com.jiayuezh.hello.service.HelloService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@RestController
public class HelloController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    private HelloService service;

    private RestTemplate template = new RestTemplate();

    @RequestMapping("/hi")
    private String say(){
        LOGGER.info("sayhi start.");
        return "piu piu piu";
    }

    @RequestMapping("/input")
    public String inputId(@RequestParam("id") String id){
        LOGGER.info("store start.");
        return "POST id:" + id;
    }

    @RequestMapping("/store")
    public ResponseDto storeUser(@RequestBody UserDto  user, HttpServletRequest request){
        System.out.println("key:" + user.getId()+":"+user.getName());
        return service.storeUser(user);
    }

    @RequestMapping("/set")
    public ResponseDto updateUser(@RequestParam("id") String id, @RequestParam("name") String name) {
        UserDto user = new UserDto(id,name);
        return  service.updateUser(user);
    }

    @RequestMapping("/add")
    public void addUser(@RequestBody UserDto dto) {
        service.addUser(dto);
        return ;
    }
}

UserDto

package com.jiayuezh.hello.dto;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class UserDto {
    private String name;
    private String id;


    public UserDto(){}

    public UserDto(String id, String name)
    {
        this.id = id;
        this.name = name;
    }




}

UserMapper

package com.jiayuezh.hello.mapper;

import com.jiayuezh.hello.model.UserEntity;
import tk.mybatis.mapper.common.Mapper;


public interface UserMapper extends Mapper<UserEntity> {
}

UserEntity

package com.jiayuezh.hello.model;

import com.sun.javafx.beans.IDProperty;
import jdk.nashorn.internal.ir.annotations.Immutable;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

@Getter
@Setter
@Table(name="t_user")
public class UserEntity {


    @Column(name = "name")
    private String id;

    private String name;

    private  String data;

}

HelloServiceImp

package com.jiayuezh.hello.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jiayuezh.hello.dto.UserDto;
import com.jiayuezh.hello.dto.ResponseDto;
import com.jiayuezh.hello.mapper.UserMapper;
import com.jiayuezh.hello.model.UserEntity;
import com.jiayuezh.hello.service.HelloService;
import com.jiayuezh.hello.utils.Constents;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.*;
import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;

import java.util.Arrays;



@Service
public class  HelloServiceImpl implements HelloService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseDto storeUser(UserDto dto){

        return new ResponseDto(Constents.SUCCESS_STATUS, Constents.SUCCESS);
    }

    @Override

    public ResponseDto updateUser(UserDto dto) {
        String url = "http://localhost:6667/store";
/*
        System.out.println("setUser,id"+user.getId()+"name"+user.getName());
        String id = user.getId();
        String name = user.getName();
*/

        String body = JSONObject.toJSONString(dto);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

/*
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add(id,name);
        System.out.println("paramMap"+paramMap.toString());
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println("httpEntity"+httpEntity.toString());
        System.out.println("restTemplate"+restTemplate.toString());
*/

        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        System.out.println("result:status:[" + result.getStatusCode()+ "]body:["+result.getBody()+"]");
        return new ResponseDto(Constents.SUCCESS_STATUS, Constents.SUCCESS, result.getBody());

    }

    @Override
    public void addUser(UserDto dto) {
        System.out.println("enter addUser");
        UserEntity userEntity = new UserEntity();
        userEntity.setId(dto.getId());
        userEntity.setName(dto.getName());
        userEntity.setData("setDataDone");
        System.out.println("id:" + userEntity.getId() + ",name:" + userEntity.getName());
        userMapper.insert(userEntity);

    }

}

HelloService

package com.jiayuezh.hello.service;

import com.jiayuezh.hello.dto.UserDto;
import com.jiayuezh.hello.dto.ResponseDto;

import javax.servlet.http.HttpServletRequest;

public interface HelloService {
    public ResponseDto storeUser(UserDto dto);
    public ResponseDto updateUser(UserDto dto) ;
    public void addUser(UserDto dto) ;
}

Contents

package com.jiayuezh.hello.utils;

/**
 * 常量类
 */
public interface Constents {
    String SUCCESS = "Success";
    String SUCCESS_STATUS = "0000";
    String SLASH = "/";
    String COLON = ":";
    String FAILED_STATUS = "0001";
    String FAIL = "Fail";
    String PHYSICAL = "physical";
}

启动类

package com.jiayuezh.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@RestController
@MapperScan("com.jiayuezh.hello.mapper")
@PropertySource(value="database.properties")
public class HelloApplication {


	public static void main(String[] args) {
		SpringApplication.run(HelloApplication.class, args);
	}

	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.jiayuezh</groupId>
	<artifactId>hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>hello</name>
	<description>Demo project for Spring Boot</description>

	<properties>
<!--		<java.version>1.8</java.version>
        <alibaba.fasterjson.version>1.2.58</alibaba.fasterjson.version>
        <kotlin.version>1.2.71</kotlin.version>
        <kotlin.compiler.incremental>true</kotlin.compiler.incremental>
        <tk.mybatis.version>2.1.5</tk.mybatis.version>
		<druid.version>1.1.10</druid.version>
		<mybatis.version>1.3.2</mybatis.version>
		<lombok.version>1.18.12</lombok.version>-->


        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <druid.version>1.1.10</druid.version>
        <mybatis.version>1.3.2</mybatis.version>
        <tk.mybatis.version>2.1.5</tk.mybatis.version>
        <swagger.version>2.9.2</swagger.version>
        <alibaba.fasterjson.version>1.2.58</alibaba.fasterjson.version>
        <lombok.version>1.18.12</lombok.version>

  </properties>

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
                </dependency>-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- 添加MySQL数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 添加数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${tk.mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${alibaba.fasterjson.version}</version>
        </dependency>
        <!--lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>


    </dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>1.8</jvmTarget>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>testCompile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
	</build>
</project>

版权声明:本文为jass535原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。