栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用JPA保留两个实体

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用JPA保留两个实体

当持久保存关系的非所有权方的一个实例(包含“ mappedBy”并且在您的情况下为“消费者”)时,您必须 始终
确保将关系的双方都设置为具有预期的级联工作。

您当然应该总是这样做,以确保您的域模型正确。

Consumer c = new Consumer();ProfilePicure p = new ProfilePicture();c.setProfilePicture(p);//see implementation//persist c

消费者.java

    @Entity    @Table(name = "Consumer")    @NamedQueries({...})    public class Consumer implements Serializable {        @Id        @GeneratedValue(strategy = GenerationType.IDENTITY)        @Basic(optional = false)        @Column(name = "id")        private Integer id;        @Basic(optional = false)        @NotNull        @Size(min = 1, max = 50)        @Column(name = "userName")        private String userName;        @oneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")        private ProfilePicture profilePicture;        public void setProfilePicture(ProfilePicture profilePicture){ //SET BOTH SIDES OF THE RELATIonSHIP this.profilePicture = profilePicture; profilePicture.setConsumer(this);        }}

始终封装添加/删除关系,然后可以确保正确性:

public class Parent{private Set<Child> children;public Set<Child> getChildren(){    return Collections.unmodifiableSet(children); //no direct access:force clients to use add/remove methods}public void addChild(Child child){    child.setParent(this);     children.add(child);}public class Child(){    private Parent parent;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/494853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号