SpringBoot框架的搭建就不在说了,文章很多,jpa支持OneToOne,OneToMany,ManyToOne,ManyToMany的配置,在开发上相当效率,另外Jpa在没有实体的情况下执行Sql查询,不需要映射,非常强大。
下面介绍一下jpa结合java1.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层
@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();
}