Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc Spring数据Jpa:使用@ManyToOne保存实体_Spring Mvc_Spring Boot_Spring Data Jpa - Fatal编程技术网

Spring mvc Spring数据Jpa:使用@ManyToOne保存实体

Spring mvc Spring数据Jpa:使用@ManyToOne保存实体,spring-mvc,spring-boot,spring-data-jpa,Spring Mvc,Spring Boot,Spring Data Jpa,我在使用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") priva

我在使用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;
JpaRepository中是否定义了一个方法可以做到这一点,或者,我应该添加一个服务层并像下面那样定义我的方法,还是在存储库中定义一个自定义方法

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

在没有
服务
层的情况下构建解决方案不是一个好的做法,因为您将不得不手动处理
事务
传播
,并且您将面临
脏读
的风险

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