Spring Boot 2.0.3 Spring data jpaを統合し、添削の機能を実現しました.
3335 ワード
Spring Bootのフレームワークの構築はもちろん、記事が多く、jpaはOneToOne、OneToMany、ManyToOne、ManyTonyの配置をサポートしています.開発上はかなり効率的です.
以下では、jpaとjava 1.8の関数を組み合わせたプログラミング思想を紹介します.
1.まずはBaseRepositoryを作成します.
以下では、jpaとjava 1.8の関数を組み合わせたプログラミング思想を紹介します.
1.まずはBaseRepositoryを作成します.
@NoRepositoryBean
public interface BaseRepository extends Repository {
Optional findOne(ID id);
S save(S entity);
Optional findById(ID primaryKey);
Iterable findAll();
long count();
void delete(T entity);
boolean existsById(ID primaryKey);
}
2、実体類の作成@Entity(name = "Student")
public class Student implements Serializable{
private static final long serialVersionUID = 5537592547914489373L;
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private String sex;
private String phone;
private String address;
3,DAO層を作成するpublic interface StudentRepository extends BaseRepository{
List> findByNameLike(String surname);
List> findAll(Specification specification);
Optional findOne(Integer id);
Optional findByName(String name);
@Query("SELECT id,address,age,classNo,name,phoneNum,sex FROM Student ")
Stream> streamAllStudents();
@Async
CompletableFuture> readAllBy();
}
4,サービス層@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public List> findAll() {
return studentRepository.findAll(null);
}
public Student getStudent(int id) {
Optional findOne = studentRepository.findOne(id);
Student student = findOne.get();
return student;
}
@Transactional
public List> streamAllStudents() {
List> studentList;
try (Stream> customers = studentRepository.streamAllStudents()) {
studentList = customers.collect(Collectors.toList());
}
return studentList;
}
public List> readAllBy() throws InterruptedException, ExecutionException {
CompletableFuture> future = studentRepository.readAllBy();
CompletableFuture.supplyAsync(this::streamAllStudents);
return future.get();
}
}
5,WEB層@RestController
@RequestMapping("/springboot_jpa")
public class StudentWeb {
@Autowired
private StudentService studentService;
//
@RequestMapping("/student/findAll")
public List> findAll() {
return studentService.findAll();
}
@RequestMapping("/student/jdk8text")
private Student getOne() {
Student student = studentService.getStudent(1);
return student;
}
/**
*
*
* @return
* @Description:
* @author Bern_Liu
* @version :2018 6 22 2:09:18
*/
@RequestMapping("/student/getListStudent")
private List> getListStudent() {
List> totalStudent = studentService.streamAllStudents();
return totalStudent;
}
/**
* JSON name:xxx
*
* @return
* @Description:
* @author Bern_Liu
* @version :2018 6 22 2:09:18
*/
@RequestMapping("/student/readAllBy")
private List> readAllBy() throws InterruptedException, ExecutionException {
return studentService.readAllBy();
}