在创建一方的entity是添加一个增加多方的方法:

package com.sim.mfg.data.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapKeyColumn;
import javax.persistence.MapKeyEnumerated;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Where;

import com.sim.mfg.data.domain.type.GoodType;
import com.sim.mfg.data.domain.type.RelationshipType;

/**
 *
 * @author damien
 *
 */
@Entity
@Table(name = "GOOD")
@Where(clause="enabled=1") //Used for logical delete, disabled objects are always hidden
public class Good extends AMfgObject implements Serializable {

/** serialVersionUID */
    private static final long serialVersionUID = -7656499731749432022L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "GOOD_ID", nullable = false)
    private Long id;

@Enumerated(EnumType.STRING)
    @Column(name = "TYPE", nullable = false)
    private GoodType type;
    
    @Column(name = "STATUS")
    private String status;

@Column(name = "PRODUCTION_DATE")
    private Date productionDate;
    
    @Column(name = "EXPIRY_DATE")
    private Date expiryDate;
    
    @JoinColumn(name = "PRODUCT_ID", nullable = false)
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Product product;
    
    @JoinColumn(name = "FILL_ID")
    @ManyToOne(fetch = FetchType.LAZY)
    private Fill fill;
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "good", cascade = CascadeType.ALL)
    @MapKeyColumn(name="TYPE")
    @MapKeyEnumerated(EnumType.STRING)
    private Map<RelationshipType, Relationship> relationships = new HashMap<RelationshipType, Relationship>();
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "good")
    private Set<Code> codes;
    
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "good",cascade=CascadeType.ALL)
    private Set<GoodStatus> goodStatus;
    /**
     * Empty constructor
     */
    public Good(){}
    
    /**
     * Good constructor
     * @param type
     */
    public Good(GoodType type) {
        super();
        this.type = type;
    }
    
    /**
     * Good constructor
     * @param type
     * @param product
     */
    public Good(GoodType type, Product product) {
        this(type, product, null, null);
    }
    
    /**
     * Good constructor
     * @param type
     * @param product
     * @param productionDate
     * @param expiryDate
     */
    public Good(GoodType type, Product product, Date productionDate, Date expiryDate) {
        super();
        this.type = type;
        this.product = product;
        this.productionDate = productionDate;
        this.expiryDate = expiryDate;
    }

@Override
    public void editFrom(AMfgObject object) {
        // Not needed for this object
    }
    
    /**
     * Get relationship for given type
     * @param type
     * @return
     */
    public Relationship getRelationship(RelationshipType type) {
        return relationships.get(type);
    }
    
    /**
     * Add relationship of given type with the given good
     * @param type
     * @param withGood
     */
    public void addRelationship(RelationshipType type, Good withGood) {
        if (!relationships.containsKey(type))
            relationships.put(type, new Relationship(this, type));
        relationships.get(type).add(withGood);
    }
    
    /**
     * Removed relationship of given type with the given good
     * @param type
     * @param withGood
     */
    public void removeRelationship(RelationshipType type, Good withGood) {
        if (relationships.containsKey(type))
            relationships.get(type).remove(withGood);            
    }
    
    /**
     * Removed all relationships with the given good
     * @param withGood
     */
    public void removeAllRelationships(Good withGood) {
        relationships.values().forEach(relationship -> relationship.remove(withGood));
    }
    
    public Long getId() {
        return id;
    }

public void setId(Long id) {
        this.id = id;
    }

public String getStatus() {
        return status;
    }

public void setStatus(String status) {
        this.status = status;
    }

public Product getProduct() {
        return product;
    }

public void setProduct(Product product) {
        this.product = product;
    }

public Fill getFill() {
        return fill;
    }

public void setFill(Fill fill) {
        this.fill = fill;
    }

public Map<RelationshipType, Relationship> getRelationships() {
        return relationships;
    }

public void setRelationships(Map<RelationshipType, Relationship> relationships) {
        this.relationships = relationships;
    }
    
    public GoodType getType() {
        return type;
    }

public void setType(GoodType type) {
        this.type = type;
    }

public Set<Code> getCodes() {
        return codes;
    }

public void setCodes(Set<Code> codes) {
        this.codes = codes;
    }

public Date getProductionDate() {
        return productionDate;
    }

public void setProductionDate(Date productionDate) {
        this.productionDate = productionDate;
    }

public Date getExpiryDate() {
        return expiryDate;
    }

public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }
    
    public Set<GoodStatus> getGoodStatus() {
        return goodStatus;
    }

public void setGoodStatus(Set<GoodStatus> goodStatus) {
        this.goodStatus = goodStatus;
    }

/**
     * add GoodStatus directly
     * @param goodStatus
     */
    public void addGoodStatus(GoodStatus goodStatus){
        this.goodStatus.add(goodStatus);
        goodStatus.setGood(this);   //不设置这句就不会执行update语句!!
    }
}
多的一方:

package com.sim.mfg.data.domain;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Where;

import com.sim.mfg.data.domain.event.EndUserScan;
import com.sim.mfg.data.domain.type.GoodStatusType;

@Entity
@Table(name = "GOODSTATUS")
@Where(clause = "enabled=1")
public class GoodStatus extends AMfgObject implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = -1279190303132720639L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "GOODSTATUS_ID", nullable = false)
    private Long id;

@Enumerated(EnumType.STRING)
    @Column(name = "TYPE")
    private GoodStatusType type;

@Column(name = "VALUE")
    private String value;

@JoinColumn(name = "ENDUSERSCAN_ID", nullable = false)
    @OneToOne(optional = true, fetch = FetchType.LAZY)
    private EndUserScan scan;
    
    @JoinColumn(name = "GOOD_ID")
    @ManyToOne(optional = true, fetch = FetchType.LAZY,cascade={CascadeType.MERGE,CascadeType.REFRESH})
    private Good good;

public GoodStatus() {
        super();
    }

public GoodStatusType getType() {
        return type;
    }

public void setType(GoodStatusType type) {
        this.type = type;
    }

public String getValue() {
        return value;
    }

public void setValue(String value) {
        this.value = value;
    }

public EndUserScan getScan() {
        return scan;
    }

public void setScan(EndUserScan scan) {
        this.scan = scan;
    }

public Long getId() {
        return id;
    }

public void setId(Long id) {
        this.id = id;
    }

public Good getGood() {
        return good;
    }

public void setGood(Good good) {
        this.good = good;
    }

@Override
    public void editFrom(AMfgObject object) {
        // TODO Auto-generated method stub

}

}
在GoodService里:

@Override
    public void addstatus(Long goodId, GoodStatus goodStatus) {
        Good good=goodRepository.findOne(goodId);
        good.addGoodStatus(goodStatus);
        goodRepository.save(good);
    }

工作中遇到的问题--Hibernate一对多保存简化Service层代码的更多相关文章

  1. 工作中遇到的问题--JPA 一对多查询

    /**     *  order by gs.updateDate desc          *  SELECT gs FROM GoodStatus gs WHERE gs IN(     * @ ...

  2. 工作中遇到的问题--Hibernate注解添加在一方和多方的区别

    以Good和GoodStatus为例: 一.注解仅添加在一方: @Entity@Table(name = "GOOD")@Where(clause="enabled=1& ...

  3. Hibernate 一对多 保存和修改数据

    Student和Sclass表,Student外键cid是Sclass的cid create table sclass( cid ) primary key, cname ) )go create t ...

  4. 工作中遇到的vscode配合eslint完成保存为eslint格式

    vscode个人设置 // vscode的个人设置配置 { "workbench.iconTheme": "vscode-icons", "workb ...

  5. Hibernate一对多操作

    --------------------siwuxie095 Hibernate 一对多操作 以客户和联系人为例,客户是一,联系人是多 即 一个客户里面有多个联系人,一个联系人只能属于一个客户 注意: ...

  6. Hibernate 一对多

    表与表之间关系回顾(重点) 1 一对多 (1)分类和商品关系,一个分类里面有多个商品,一个商品只能属于一个分类 (2)客户和联系人是一对多关系 - 客户:与公司有业务往来,百度.新浪.360 - 联系 ...

  7. hibernate 一对多双向关联 详解

    一.解析: 1.  一对多双向关联也就是说,在加载班级时,能够知道这个班级所有的学生. 同时,在加载学生时,也能够知道这个学生所在的班级. 2.我们知道,一对多关联映射和多对一关联映射是一样的,都是在 ...

  8. Hibernate一对多OnetoMany

    ------------------------Hibernate一对多OnetoMany 要点: 配置在一端. 1.如果是单向关联,即只在一端配置OneToMany,多端不配置ManyToOne.则 ...

  9. Hibernate一对多关系操作

    1.创建两个实体类. 一个实体类是商品类,另一个实体类是商品的分类类. 在一对多关系的两个实体中,在编写实体类时必须要遵循以下规则: (1)在一的那一方的实体中,必须要有一个私有的多那一方的实体对象属 ...

随机推荐

  1. 2014年2月份第4周51Aspx源码发布详情

    AM自定义报表管理系统源码  2014-2-28 [VS2010]源码描述: 本系统有以下特色之处: 1.一套软件,多点登陆,根据权限不同共同管理报表,适应于前期获取客户需求报表字段使用. 2.客户自 ...

  2. Android开发中的ANR问题如何避免?

    在Android中, Activity Manager 和 Window Manager system services 会监控每个程序的运行,当程序出现如下三种种情况的时候就会弹出ANR的提示对话框 ...

  3. git vs svn

    http://www.tuicool.com/articles/e2MnAb Git与SVN的不同之处 svn为集中化的版本控制,svn获取最新的版本或者提交更新,历史记录等信息每次都要连接中央版本库 ...

  4. BZOJ 1034 泡泡堂

    贪心可过.原来浙江省选也不是那么难嘛.. 作者懒,粘的题解.此题类似于田忌赛马的策略,只要站在浙江队一方和站在对手一方进行考虑即可. #include<iostream>#include& ...

  5. Ubuntu安装Fcitx(小企鹅五笔输入法)

    安装配置如下: 1. 安装 fcitx sudo apt-get install fcitx 2. 配置默认输入法为 fcitx im-switch -s fcitx // 注意无须加 sudo 3. ...

  6. JQuery源码分析(四)

    jQuery多库共存处理 多库共存换句话说可以叫无冲突处理. 总的来说会有2种情况会遇到: 1.$太火热,jQuery采用$作为命名空间,不免会与别的库框架或者插件相冲突. 2.jQuery版本更新太 ...

  7. Redis - sort set类型操作

    sort set操作:sort set在set基础上增加了一列用于存储顺序序列设置操作:zadd key:        zadd key sortnum value        指定key增加元素 ...

  8. [动态规划]状态压缩DP小结

     1.小技巧 枚举集合S的子集:for(int i = S; i > 0; i=(i-1)&S) 枚举包含S的集合:for(int i = S; i < (1<<n); ...

  9. 重学STM32---(七) FSMC+LCD

    关于FSMC+LCD第一次学习完时候,自己也还是对这个不清不白,时而清楚,时而糊涂.这一次再次学习的话,不能在这样了,仔仔细细把STM32参考手册,原子的LCD实验看了一遍,又在网上找了好些关于FSM ...

  10. Ecshop安装过程中的的问题:cls_image::gd_version()和不支持JPEG

    在安装Ecshop的时候,遇到两个问题: 1.Strict Standards: Non-static method cls_image::gd_version() should not be cal ...