【问题标题】:Spring Data Jpa: save an entity with @ManyToOneSpring Data Jpa:使用@ManyToOne 保存实体
【发布时间】:2015-10-08 22:59:06
【问题描述】:

我正在使用spring boot,我有这两个类

@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;

和类别类:

@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();
    }

【问题讨论】:

    标签: spring-mvc spring-boot spring-data-jpa


    【解决方案1】:

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

    在没有service 层的情况下构建解决方案不是一个好习惯,因为您必须手动处理transactionspropagations,并且您将面临dirty reads 的风险。

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 2013-05-09
      • 2018-09-04
      • 1970-01-01
      • 2022-11-29
      • 2018-04-20
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多