1. 程式人生 > >springboot整合data-jpa

springboot整合data-jpa

1.新增依賴

<!--lombok小工具 -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
</dependency>

<!--mysql依賴-->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency> <!--data-jpa依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2.application.properties

#mysql配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root spring.datasource.password=root spring.datasource.url=jdbc:mysql://***:3306/competition?characterEncoding=utf-8&useSSL=false #data jpa配置 spring.jpa.show-sql=true
3.entity類

package com.example.competition.dao.entity;

import lombok.Data;
import org.hibernate.annotations.DynamicUpdate
; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; @DynamicUpdate @Entity @Data public class Student { @Id private Integer studentId; private String studentNo; private String studentName; private Integer groupId; private Integer studentSpecialtyId; private Integer studentGrade; private Integer studentStatus; private Date createTime; private Date updateTime; }
4.repository

public interface StudentRepository extends JpaRepository<Student, Integer> {

    Page<Student> findByStudentStatus(Pageable pageable, Integer status);

    Student findOne(Integer studentId);
}
5.test

@Autowired
private StudentRepository repository;

@Test
public void findByStudentStatus() {
    PageRequest pageRequest = new PageRequest(0, 10);
    Page<Student> result = repository.findByStudentStatus(pageRequest, 1);
    Assert.assertEquals(1, result.getTotalElements());
}

@Test
public void findOne() {
    Student result = repository.findOne(1);
    System.out.println(result.toString());
}