So basically what I'm trying to achieve is, to create a new recipe while specifying already existing entities (ingredients and author). From my experience in NestJs and TypeOrm I thought it would also be somehow possible to just pass an ID of for example an existing author(User) or a list of existing Ids of ingredients and data JPA would automatically connect them.
The only thing I managed to get working is creating new ingredients with a JSON post request of a recipe that contains a list of ingredients by using the @JsonManagedReference annotation. But I don't want to create new ingredients, I want to reference existing ones(same for the author).
POST - create recipe endpoint
@PostMapping
fun createRecipe(@RequestBody recipe: Recipe) {
recipeService.createRecipe(recipe)
}
Recipe Entity:
@Entity
@Table(name = "recipe")
class Recipe(
@Column(name = "title", nullable = false)
val title: String,
@Column(name = "description", nullable = false)
val description: String,
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
val author: User,
@ManyToMany(fetch = FetchType.EAGER, cascade = [CascadeType.ALL])
@JoinTable(
joinColumns = [JoinColumn(name = "recipe_id")],
inverseJoinColumns = [JoinColumn(name = "ingredient_id")],
)
@JsonManagedReference
val ingredients: Set<Ingredient>?,
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long? = null,
)
User Entity:
@Entity
@Table(name = "member")
class User (
@Column( name = "first_name", nullable = false)
val firstName: String,
@Column(name = "last_name", nullable = false)
val lastName: String,
@Column(name = "email", nullable = false, unique = true)
val email: String,
@Column(name = "password", nullable = false)
val password: String,
@OneToMany(mappedBy = "author")
val recipes: MutableSet<Recipe> = mutableSetOf(),
//---------- Optional am ende am besten ----------------
@Column(name = "image" ,nullable = true)
val imageUrl: String? = null,
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long? = null,
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
val createdAt : Date? = null,
)