Spring Data Jpa:使用@ManyToOne 保存一个实体

Spring Data Jpa: save an entity with @ManyToOne

我正在使用 spring 启动,我有这两个 classes

@Entity
@Table(name="products")
public class Product implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idProduit;
 //other attributes..
@ManyToOne
@JoinColumn(name="idCategory")
private Category category;

和类别class:

@Entity
public class Category implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idcategory;
//attributes...
@OneToMany(mappedBy="category")
private Collection<Product> products;

我想编写一个方法来保存产品

public long saveProduct(Product p, Long idCat)

JpaRepository 中是否定义了可以执行此操作的方法,或者我应该添加一个服务层并像下面这样定义我的方法,还是在 Repository 中将其定义为自定义方法?

public long saveProduct(Product p, Long idCat){
    Category c=getCategory(idCat);
    p.setCategory(c);
    em.persist(p);
    return p.getIdProduct();
    }

我认为你应该添加一个服务层并定义一个 transactional 方法来处理像 CategoryNotFoundException 这样的异常(当 Category c=getCategory(idCat) 触发一个时), DataIntegrityViolationException.....

在没有 service 层的情况下构建解决方案不是一个好的做法,因为您将不得不手动处理 transactionspropagations,并且您将面临 dirty reads.