基础环境搭建
代码配置
依赖添加到pom中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
创建一个DO
package com.alibaba.middleware.DO;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "dream")
public class DreamDo {
@Id
private Long id;
@Column(length = 32)
private String url;
@Column(length = 32)
private String len;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLen() {
return len;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setLen(String len) {
this.len = len;
}
}
创建一个DAO
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
@Component
@Repository
public interface DreamDao extends JpaRepository<DreamDo,Long> {
}
添加配置到application.properties
#通用数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mdata?charset=utf8mb4&useSSL=false
spring.datasource.username=root
spring.datasource.password=你的密码
# Hikari 数据源专用配置
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
# JPA 相关配置
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
创建相应DB数据库
create table mdata;
CREATE TABLE dream
(id Long,
url varchar(255),
len varchar(255)
);
添加对应代码到Controller
@RestController
@RequestMapping(value = "/api", method = RequestMethod.GET)
public class ApiController {
@Autowired
private DreamDao dreamDao;
@RequestMapping(value = "/save")
@ResponseBody
public HashMap<String, Object> save() {
HashMap<String, Object> map = new HashMap<String, Object>();
DreamDo dreamDo = new DreamDo();
dreamDo.setId(2L);
dreamDo.setUrl("http://baidu.com");
dreamDo.setLen(String.valueOf("http://baidu.com".length()));
dreamDao.save(dreamDo);
map.put("success", "True");
return map;
}
}
运行代码
参考资料: