moethata
moethata

Reputation: 3571

Spring Data Jpa: save an entity with @ManyToOne

I m working with spring boot, i have these two 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;

and category class :

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

i want to code a methode to save product

public long saveProduct(Product p, Long idCat)

Is there a method defined in JpaRepository which can do this or, should i add a service Layer and define my method like below or define it a custom method in Repository ?

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

Upvotes: 1

Views: 3787

Answers (1)

Rafik BELDI
Rafik BELDI

Reputation: 4158

I think you should add a service Layer and define a transactional method in order to handle exceptions like CategoryNotFoundException (when Category c=getCategory(idCat) fires one) , DataIntegrityViolationException....

Building a solution without a service Layer isn't a good practice, since you will have to handle transactions and propagations manually and you will risk having dirty reads.

Upvotes: 1

Related Questions