问题
I have a parent object lets say Campaign and child object Ad Segments. Campaign is holding one to many relation with Ad Segments. following is the annotations I defined.
class CampaignModel {
OneToMany(mappedBy="campaign", cascade=CascadeType.PERSIST, fetch = FetchType.EAGER)
@Setter
@Column(updatable=false)
private List<AdSegmentModel> segments;
.....
}
class AdSegmentModel {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="campaign_id")
@Getter
@Setter
private CampaignModel campaign;
Requirements :
When we insert into Campaign Model, ad segments should also get inserted.
When we retrieve Campaign Model, corrosponding ad segments should get retrieved.
Ad Segments are non- updatable. When we update campaigns, nothing should happen in Ad segments table.
Issues facing:
When I do CascadeType.PERSIST , campaign is getting inserted but nothing happen in Ad segments table. (Reason : https://www.mkyong.com/hibernate/cascade-jpa-hibernate-annotation-common-mistake/). I dont know the solution as I dont want to give CascadeType.SAVE_UPDATE. Because it will cause un ecessary operations in case of update campaigns.
When i Retrieve campaigns, it is giving me duplicate record. Reason is it is doing left outer join with Ad segments table and since ad segment table has multiple rows corrosponding to one row in campaign table, it is givig duplicate records.
For saving Campiagn Object :
try {
Session session = sessionFactory
.getCurrentSession();
long id = (long) session.save(newCampaign);
return id;
} catch (HibernateException e) {
throw new DependencyException("Cannot save campaign", e);
}
For getting campaign :
Session session = sessionFactory
.getCurrentSession();
List<Criterion> criteria = new ArrayList<>();
criteria.add(Restrictions.eq("obfuscatedEntityId",
obfuscatedEntityId));
List<CampaignModel> campaignModels = HibernateUtils
.loadObjectsFromHibernate(session, criteria, CampaignModel.class);
System.out.println("size inside builder functionsss"+campaignModels.size());
return campaignModels;
Read this : Hibernate : CascadeType.PERSIST does not work but CascadeType.ALL to save object My question is if on updating parent object, nothing should happen in child table which annotation should I use? Is it safer to use SAVE_UPDATE?
Please help!
来源:https://stackoverflow.com/questions/41084320/confusion-in-giving-hibernate-association-annotation