JPA实现数据的更新操作
2022/3/5 6:17:13
本文主要是介绍JPA实现数据的更新操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JPA实现数据的更新操作
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; }
方式一 : 通过 jpa提供的save方法实现更新
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); }); } }
方式二: 通过jql实现更新
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()); } }
这篇关于JPA实现数据的更新操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?
- 2024-05-30java excel上传--poi
- 2024-05-30安装笔记本应用商店的pycharm,再安排pandas等模块,说是没有打包工具?
- 2024-05-29java11新特性