本文将介绍一些 Spring Data JPA 使用过程中容易出错或者需要注意的一些点的最佳实践方案;并会提供对 Spring Data JPA 核心部分源码分析并自己实现一个MyJPA(附源码);
https://vimeo.com/661399278
密码1321
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
@Transactional @Override public void deletePaymentPlan (Long id) { PaymentPlan paymentPlan = getPaymentPlanEntity(id); paymentPlan.setDeleted(true ); paymentPlanRepository.save(paymentPlan); } ``` 方式1 :并不推荐,不够灵活,还需要人工对每个 Entity 写sql,万一字段变动怎么办?如果我需要物理删除又怎么办? ```java @SQLDelete (sql = "UPDATE t_user SET deleted = true WHERE id=?" )@Entity @Table (name = "t_user" )public class User { @Id @GeneratedValue private Long id; private String name; private boolean deleted = false ; } @Test void sqlDelete () { final Optional<User> byId = userRepository.findById(1L ); userRepository.delete(byId.get()); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
@Entity public class User { @OneToMany (mapperBy="user" , fetch=FetchType.EAGER) private List<Address> addresses; } @Entity public class Address { @ManyToOne @JoinColumn (name = "user_id" ) private User user; } @Test public void test () { userRepository.findAll(); }
1 2 3
@OneToOne (cascade = CascadeType.ALL)@JoinColumn (name = "receipt_id" )private Receipt receipt;
1 2 3
@ManyToOne @JoinColumn (name = "receipt_batch_type_id" , foreignKey = @ForeignKey (ConstraintMode.NO_CONSTRAINT))private ReceiptBatchType receiptBatchType;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
@Override public Page<PaymentPlanDTO> getPaymentPlans (PaymentPlanQuery paymentPlanQuery) { final Long serviceAccountNumber = paymentPlanQuery.getServiceAccountNumber(); return paymentPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> { final List<Predicate> predicates = new ArrayList<>(); if (serviceAccountNumber != null ) { predicates.add( criteriaBuilder.and( criteriaBuilder.equal(root.get("serviceAccountNumber" ), serviceAccountNumber) ) ); } predicates.add( criteriaBuilder.and( criteriaBuilder.equal(root.get("deleted" ), false ) ) ); return criteriaBuilder.and(predicates.toArray(new Predicate[0 ])); }).map(MAPPER::toDTO); }
1 2 3 4 5 6 7
@Autowired private EntityManager entityManager;@PersistenceContext private EntityManager entityManager;
1 2 3 4 5 6 7 8 9 10 11
@DynamicUpdate public class User () {}@Test public void test () { User user = userRepository.findById(1L ); user.setName("kok" ); userRepository.save(user); }
1 2 3 4 5
jdbc.url=jdbc:mysql: