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

时间:2022-01-09 08:54:08

在创建一方的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);
    }