基础环境搭建

代码配置

依赖添加到pom中

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>mysql</groupId>
  7. <artifactId>mysql-connector-java</artifactId>
  8. <version>8.0.11</version>
  9. </dependency>

创建一个DO

  1. package com.alibaba.middleware.DO;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.Id;
  5. import javax.persistence.Table;
  6. @Entity
  7. @Table(name = "dream")
  8. public class DreamDo {
  9. @Id
  10. private Long id;
  11. @Column(length = 32)
  12. private String url;
  13. @Column(length = 32)
  14. private String len;
  15. public Long getId() {
  16. return id;
  17. }
  18. public void setId(Long id) {
  19. this.id = id;
  20. }
  21. public String getLen() {
  22. return len;
  23. }
  24. public String getUrl() {
  25. return url;
  26. }
  27. public void setUrl(String url) {
  28. this.url = url;
  29. }
  30. public void setLen(String len) {
  31. this.len = len;
  32. }
  33. }

创建一个DAO

  1. import org.springframework.data.jpa.repository.JpaRepository;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.stereotype.Repository;
  4. @Component
  5. @Repository
  6. public interface DreamDao extends JpaRepository<DreamDo,Long> {
  7. }

添加配置到application.properties

  1. #通用数据源配置
  2. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/mdata?charset=utf8mb4&useSSL=false
  4. spring.datasource.username=root
  5. spring.datasource.password=你的密码
  6. # Hikari 数据源专用配置
  7. spring.datasource.hikari.maximum-pool-size=20
  8. spring.datasource.hikari.minimum-idle=5
  9. # JPA 相关配置
  10. spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
  11. spring.jpa.show-sql=true
  12. spring.jpa.hibernate.ddl-auto=create

创建相应DB数据库

  1. create table mdata;
  2. CREATE TABLE dream
  3. (id Long,
  4. url varchar(255),
  5. len varchar(255)
  6. );

添加对应代码到Controller

  1. @RestController
  2. @RequestMapping(value = "/api", method = RequestMethod.GET)
  3. public class ApiController {
  4. @Autowired
  5. private DreamDao dreamDao;
  6. @RequestMapping(value = "/save")
  7. @ResponseBody
  8. public HashMap<String, Object> save() {
  9. HashMap<String, Object> map = new HashMap<String, Object>();
  10. DreamDo dreamDo = new DreamDo();
  11. dreamDo.setId(2L);
  12. dreamDo.setUrl("http://baidu.com");
  13. dreamDo.setLen(String.valueOf("http://baidu.com".length()));
  14. dreamDao.save(dreamDo);
  15. map.put("success", "True");
  16. return map;
  17. }
  18. }

运行代码

参考资料: