Spring Data JPA简单用法

什么是Spring Data JPA?

Spring Data JPA是较大的Spring Data家族的一部分,它使实现基于JPA的存储库变得很容易。这个模块处理对基于JPA的数据访问层的增强支持。它使得构建使用数据访问技术的基于spring的应用程序变得更加容易。

实现应用程序的数据访问层已经很麻烦了。为了执行简单的查询、分页和审计,必须编写太多的样板代码。Spring Data JPA的目标是通过减少实际需要的工作量来显著改进数据访问层的实现。作为开发人员,您编写存储库接口,包括自定义查找器方法,Spring将自动提供实现。

参考博客:https://blog.csdn.net/li_w_ch/article/details/110940430


简单使用:
参考博客:https://blog.csdn.net/JAVA_KX/article/details/130696773?spm=1001.2014.3001.5506

引入依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

实体类

//标识实体
@Entity 
//为注解标识的实体指定对应的数据表
@Table(name = "student")
@Data
public class Student implements Serializable {@Id //ID列标识
    @GeneratedValue(strategy = GenerationType.IDENTITY)//主键生成策略
    @Column(name = "id", length = 20, nullable = false)//列定义
    private String id;@Column(name = "name", length = 50, nullable = false)
    private String name;@Column(name = "phone", length = 11, nullable = false)
    private String phone;
}

DAO层

import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, String>, JpaSpecificationExecutor<Student> {

    @Query(value = "select * from student where name = :name and phone = :phone limit :pageSize for update nowait", nativeQuery = true)
    List<Student> findAllByName(@Param("name") String name, @Param("phone") String phone, @Param("pageSize") Integer pageSize);

    @Query(value = "select * from student where name = :name limit 1 for update nowait", nativeQuery = true)
    Student findByName(@Param("name") String studentName);
	
	@Modifying(clearAutomatically = true)
    @Transactional(rollbackFor = Exception.class)
    @Query(value = "update student set name = :name, phone = :phone  where id = :studentId", nativeQuery = true)
    int updateStudent(@Param("studentId") String id, @Param("name") String name, @Param("phone") String phone);

}

service层

@Service
public class StudentService {

    @Autowired
    StudentRepository studentDao;

    @Transactional(rollbackFor = Exception.class)
    public List<Student> fetchJobLongPolling(StudentParam studentParams) {
     
        List<Student> students;
		students = studentDao.findAllByName(studentParams.getName(),studentParams.getPhone(), 10);

        for (Student student : students) {
            int updateNumber = studentDao.updateStudent(studentParams.getId(), studentParams.getName(), studentParams.getPhone());
            if (updateNumber == 1) {
                log.info("update seccess")
            }
        }
        return students;
    }
}

你可能感兴趣的:(java,sql,数据库)