SpringBoot+Spring Data JPA
1. 添加起步依赖
<!-- spring data jpa起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.配置文件
配置项参考 SpringBoot+JPA初始化数据库表
spring.jpa.hibernate.ddl-auto=update #spring.jpa.show-sql=true #spring.jpa.generate-ddl=true
3. 建实体类 运行项目 就会在数据库中自动建表t_student
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String name;
@Column
private String homeAddress;
private Long homeTel;
}
4.建repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long>,JpaSpecificationExecutor<Student> {
}
5.建service
public interface StudentService {
Student save(Student student);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public Student save(Student student) {
return studentRepository.save(student);
}
}
6.建controller 运行项目,调用方法saveStudent就可以实现 持久化student对象到数据库
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api")
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/students")
@ResponseBody
public String saveStudent(@RequestBody Student student) {
Student savestudent = studentService.save(student);
return savestudent.getName();
}
}
浙公网安备 33010602011771号