如何使用MySQL和Spring Boot开发RESTful Web服务

本文提供了有关如何使用MySQL和Spring Boot开发RESTful Web服务的4步教程

Spring Boot是开发spring应用程序的最快方法,我们的案例中:
1. 使用MySQL数据库来存储文本文件和图像文件的路径
2. 使用Spring MVC作为架构模式和Spring RESTful Web服务来获取图像和文本。

所有这些都使用Spring Boot实现。

第一步,将JPA MYSQL和Web加入pom.xml依赖,加入方式有手工和自动,自动就是使用Idea之类开发工具的Spring导航工具生成。


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

加入的三个依赖分别是:
1. JPA:在MySQL表和java实体之间映射。

2. MySQL:使用MySQL数据库。

3. Web:提供RESTful端点,这样通过Web浏览器能够获取图像和文本

SpringBoot的启动类:


@SpringBootApplication
public class MysqlspringbootApplication {

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

第2步:设计我们的Controller,Dao和服务层,首先从数据实体开始设计:


@Entity
@Table(name = "resource_table")
public class RequestData {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name =
"File_id")
private String id;

@Column(name =
"Images_path")
private String images;

@Column(name =
"Text_path")
private String Contents;



这是一个使用JPA标注的实体类,指定Mysql表名是resource_table,ID主键是必须的,主键产生策略是使用JPA/Hibernate自动生成机制。其他都是指定对应MySQL表名。

然后建立操作该实体类的DAO工具:


public interface ApplicationDao extends CrudRepository<RequestData,Integer> {
@Query(value = "SELECT * FROM resource_table WHERE File_id=?1", nativeQuery = true)
RequestData findResource(Integer i);
}


这里只有接口,没有实现,SpringBoot框架自动帮助我们实现了,其中继承CrudRepository接口,然后将查询语句写在注释中。这是持久层编程的新风格。

再建立服务类ApplicationService:


@Service
public class ApplicationService {
@Autowired
private ApplicationDao applicationDao;

public ResponseEntity<byte[]> getImageURL() throws IOException {
RequestData requestData = applicationDao.findResource(1);
String imagePath = requestData.getImages();
RandomAccessFile f = new RandomAccessFile(imagePath, "r");
byte[] b = new byte[(int) f.length()];
f.readFully(b);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
}

public ResponseEntity<byte[]> getTextData() throws IOException {
RequestData requestData = applicationDao.findResource(1);
String s = requestData.getContents();
RandomAccessFile f = new RandomAccessFile(s,
"r");
byte[] b = new byte[(int) f.length()];
f.readFully(b);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
}
}

将数据库中的资源转发到前端。

下面建立Resftful端点ApplicationController:


@RestController
@RequestMapping(value = "/application")
public class ApplicationController {
@Autowired
private ApplicationService applicationService;

@RequestMapping(value =
"/get-image", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImagePath() throws IOException {
ResponseEntity<byte[]> responseEntity = applicationService.getImageURL();
return responseEntity;
}
@RequestMapping(value =
"/get-text", method = RequestMethod.GET)
public ResponseEntity<byte[]> getTextPath() throws IOException {
ResponseEntity<byte[]> responseEntity = applicationService.getTextData();
return responseEntity;
}
}


提供两个REST url:/application/get-image和/application/get-text

浏览器可通过这个两个url获得MySQL中文本文件和图形地址。

下面是Springboot的application.properties配置:


spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库?autoReconnect=true&useSSL=false
spring.datasource.username=用户名
spring.datasource.password=密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15

spring.jpa.generate-ddl=true


这里JPA实现指定了Hibernate,数据库微MySQL。
注意,这里指定了MySQL 5的dialect,不是普通的org.hibernate.dialect.MySQLDialect,这是针对4.0以前版本。

同时,我们设置了spring.jpa.generate-ddl=true开关,让我们JPA自动产生数据表,那么数据表的SQL放哪里?
和application.properties同一目录下建schema.sql文件,加入:


CREATE TABLE `resource_table` (
`File_id` int(10) NOT NULL AUTO_INCREMENT,
`Text_path` varchar(100) DEFAULT NULL,
`Images_path` varchar(100) DEFAULT NULL,
UNIQUE KEY `File_id` (`File_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

/*Data for the table `resource_table` */

insert into `resource_table`(`Text_path`,`Images_path`) values ('e:/text.txt','e:/image.jpg');

希望以上对你有帮助

源码下载:github

原文