entity
@Builder @Data @AllArgsConstructor @NoArgsConstructor @Entity @DynamicInsert @DynamicUpdate @Access(AccessType.FIELD) @Table(catalog = "sc", name = "t_student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; }
repository
public interface StudentRepository extends JpaRepository<Student,Integer> { }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Override public void updateStudent(StudentDto studentDto) { // 前提: 能通过id查找到对应行数据 Optional<Student> op = studentRepository.findById(studentDto.getId()); op.ifPresent(student -> { student.setName("newName"); studentRepository.save(student); }); } }
repository
@Repository public interface StudentRepository extends JpaRepository<Student, Integer> { @Transactional // 数据修改和删除,需要显示声明事务 ,直接在接口方法上添加注解 或者在调用的方法上添加注解 @Modifying @Query("update Student s set s.name =:name where s.id=:id") void updateStudent(String name, Integer id);// 注意:定义更新方法 返回值只能是void或者int,不然会报错 }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Override public void updateStudent(StudentDto studentDto) { studentRepository.updateStudent("newName2",studentDto.getId()); } }