Spring Boot 2.X 实战教程(15)使用SQL数据库

 

15.使用SQL数据库

Spring框架提供了广泛的支持使用使用SQL数据库,直接JDBC访问JdbcTemplate来完成对象关系映射技术,比如HibernateSpring Data提供了更多级别的功能:Repository直接从接口创建实现,并使用约定从方法名称生成查询。

15.1配置数据源

Javajavax.sql.DataSource接口提供了一种使用数据库连接的标准方法。传统上,'DataSource'使用URL一些凭证来建立数据库连接。

15.1.1连接到生产数据库

CREATE DATABASE IF NOT EXISTS `springboot`;

USE `springboot`;

 

也可以使用池自动配置生产数据库连接 DataSourceDataSource配置由外部配置属性控制 spring.datasource.*。例如,您可以在以下部分声明以下部分 application.properties

spring.jpa.hibernate.ddl-auto=create

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

常见问题1

错误信息:

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.

解决办法:

URL最后增加?serverTimezone=UTC。

如下所示:

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC

常见问题2

问题描述:MySQL Server 5.7中文乱码解决办法

解决办法:

修改my.ini文件

Windows路径:C:\ProgramData\MySQL\MySQL Server 5.7\my.ini

Linux路径:vim /etc/my.cnf

改为:

[client]

......

default-character-set=utf8

[mysql]

......

default-character-set=utf8

......

[mysqld]

character_set_server=utf8

......

重启服务

Windows: 控制面板->服务->MySQL57

Linux: service mysqld restart

15.2 JPASpring Data JPA

Java Persistence API是一种标准技术,可让您将对象映射到关系数据库。该spring-boot-starter-data-jpaPOM提供了上手的快捷方式。它提供以下关键依赖项:

l Hibernate:最受欢迎的JPA实现之一。

l Spring Data JPA:使实现基于JPA的存储库变得容易。

l Spring ORMsSpring Framework的核心ORM支持。

pom.xml中增加依赖包:

<!-- JPA Data -->

        

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

        

        <!-- Use MySQL Connector-J -->

        

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

        </dependency>

15.2.1实体类

传统上,JPA“实体类在persistence.xml文件中指定。使用Spring Boot,此文件不是必需的,而是使用实体扫描。默认情况下,将搜索主配置类(注释为@EnableAutoConfiguration或者@SpringBootApplication)下的所有包 

任何类别标注了@Entity@Embeddable或者@MappedSuperclass被认为是实体

典型的实体类类似于以下示例:

package com.example.demo.city;

 

import java.io.Serializable;

import javax.persistence.*;

 

/**

 * 城市实体类

 *

 * @author 大强

 *

 */

@Entity

public class City implements Serializable {

 

@Id

@GeneratedValue

private Long id;

 

@Column(nullable = false)

private String name;

 

@Column(nullable = false)

private String state;

 

// ... additional members, often include @OneToMany mappings

 

public City() {

// no-args constructor required by JPA spec

// this one is protected since it shouldn't be used directly

}

 

public City(String name, String state) {

this.name = name;

this.state = state;

}

 

public Long getId() {

return id;

}

 

public void setId(Long id) {

this.id = id;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public String getState() {

return state;

}

 

public void setState(String state) {

this.state = state;

}

 

// ... etc

 

}

15.2.2 Spring Data JPA存储库

Spring Data JPA存储库是您可以定义以访问数据的接口。JPA查询是从您的方法名称自动创建的。例如, CityRepository接口可能会声明一种findAllByState(String state)方法来查找给定状态中的所有城市。

对于更复杂的查询,您可以使用Spring DataQuery注释来注释您的方法 

Spring Data存储库通常从Repository CrudRepository 接口扩展 。如果使用自动配置,则会从包含主配置类(带有@EnableAutoConfiguration或标注的@SpringBootApplication)的包中搜索存储库 

以下示例显示了典型的Spring Data存储库接口定义:

package com.example.demo.city;

 

import org.springframework.data.repository.CrudRepository;

 

/**

 * 城市存储库

 *

 * @author 大强

 *

 */

public interface CityRepository extends CrudRepository<City, Long> {

 

}

15.2.3 Spring Data JPA控制器

Spring Data JPA提供基于注释的编程模型,其中@Controller@RestController组件使用注释来表达请求映射,请求输入,异常处理等。带注释的控制器具有灵活的方法签名,不必扩展基类,也不必实现特定的接口。

以下示例显示了由注释定义的Spring Data控制器定义:

package com.example.demo.city;

 

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

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.DeleteMapping;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.PutMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

 

/**

 * 城市控制器

 *

 * @author 大强

 *

 */

@Controller // 这意味着这个类是一个控制器

@RequestMapping(path = "/city") // 这意味着URL/city开始(在应用程序路径之后)

public class CityController {

 

@Autowired // 这意味着要得到一个名为Cityrepository的存储库

private CityRepository cityRepository;

 

/**

 * 根据主键查询单个城市

 *

 * @param id

 * @return

 */

@RequestMapping(value = "/{id}", method = RequestMethod.GET)

public @ResponseBody City getCity(@PathVariable Long id) {

return cityRepository.findById(id).orElse(new City());

}

 

/**

 * 查询所有城市列表

 *

 * @return

 */

@GetMapping(path = "/all")

public @ResponseBody Iterable<City> getAllCitys() {

// 这将返回带有citysJSONXML

return cityRepository.findAll();

}

 

/**

 * 新增城市

 *

 * @param name

 * @param state

 * @return

 */

@PostMapping(path = "/add") // 仅映射Post请求

public @ResponseBody String addCity(@RequestParam String name, @RequestParam String state) {

// @responseBody表示返回的是response,而不是视图名称

// @requestParam表示它是getpost请求的参数

City city = new City();

city.setName(name);

city.setState(state);

cityRepository.save(city);

return "新增城市成功";

}

 

/**

 * 修改城市

 *

 * @param city

 * @return

 */

@PutMapping(path = "/update") // 仅映射Put请求

public @ResponseBody String updateCity(@RequestBody City city) {

// @responseBody表示返回的是response,而不是视图名称

// @requestParam表示它是getpost请求的参数

cityRepository.save(city);

return "修改城市成功";

}

 

/**

 * 删除城市

 *

 * @param id

 * @return

 */

@DeleteMapping(path = "/{id}") // 仅映射Delete请求

public @ResponseBody String deleteCity(@PathVariable Long id) {

// @responseBody表示返回的是response,而不是视图名称

// @requestParam表示它是getpost请求的参数

City city = new City();

city.setId(id);

cityRepository.delete(city);

return "删除城市成功";

}

 

}

 

如有疑问,请观看视频:https://ke.qq.com/course/428845

 

posted @ 2019-07-30 16:34  大强的博客  阅读(304)  评论(0编辑  收藏  举报