目录
1.新建一个springboot项目,选择Create new Project
7.新建controller,service,dao,entity类
1.新建一个springboot项目,选择Create new Project
2.选择Spring initializr,再点击next
3.把需要修改的信息修改后,点击下一步
4.选择web——>Spring web,再点击下一步
5.点击finish
6.打开pom.xml文件,添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
7.新建controller,service,dao,entity类
Controller层
package com.example.demo.controller;
import com.example.demo.entity.DemoEntity;
import com.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@PostMapping("/add")
public void addChargingHub(@RequestBody DemoEntity demoEntity){
demoService.saveDemoEntity(demoEntity);
}
}
Service层
package com.example.demo.service;
import com.example.demo.dao.DemoDao;
import com.example.demo.entity.DemoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Autowired
private DemoDao demoDao;
public void saveDemoEntity(DemoEntity demoEntity) {
demoDao.save(demoEntity);
}
}
entity
package com.example.demo.entity;
import javax.persistence.*;
@Entity
@Table(name = "demo_info")
public class DemoEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", length = 255)
private String name;
@Column(name = "description", length = 255)
private String description;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Dao层
package com.example.demo.dao;
import com.example.demo.entity.DemoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface DemoDao extends JpaRepository<DemoEntity, Integer> {
}
配置文件application.properties
server.port=8088
###数据库连接信息
# 连接地址
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
# 数据库账户
spring.datasource.username = root
#数据库密码
spring.datasource.password = 123456
#数据库驱动
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true