Suppose I have a class 'Cheese' with fields type and purchaseDate, such that:
public class Cheese{
CheeseType cheeseType;
String purchaseDate;
public setPurchaseDate(String value){
purchaseDate=value;
}
public Class CheeseType{
String type;
public setType(String value){
type=value;
}
public class MyClass{
Cheese cheese = new Cheese();
cheese.setType("cedar");
cheese.setPurchaseDate("01/02/03");
// Code to get entity manager etc
em.getTransaction().begin();
em.persist(cheese);
em.getTransaction().commit();
// Code to close entity manager etc
}
Please ignore any silly mistakes in the code, I've tried to simplify my problem!
Obviously there will be many other parameters in a real world situation, but in this case: the same purchaseDate can exist many times int he database (as many times as I buy cheese!) but the 'type' already exists in the database (from previous purchases let's say). Now, each time I persist an instance of 'Cheese' to the database, a new 'CheeseType' is added, i.e. there are multiple 'cedars'. How would I go about getting each instance of 'Cheese' to check what CheeseTypes already exists and not create multiple new cedars in the database? I think I need to merge somewhere, but the examples I have seen don't seem to be the same type of thing that I'm trying to do.
If anyone has any tips, I would greatly appreciate hearing them! Apologies if I've made any rookie mistakes here!