Confusion in giving hibernate association annotation

风格不统一 提交于 2019-12-25 09:16:06

问题


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 :

  1. When we insert into Campaign Model, ad segments should also get inserted.

  2. When we retrieve Campaign Model, corrosponding ad segments should get retrieved.

  3. Ad Segments are non- updatable. When we update campaigns, nothing should happen in Ad segments table.

Issues facing:

  1. 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.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!