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

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

时间: 2024-08-03 14:25:15

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

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

以Good和GoodStatus为例: 一.注解仅添加在一方: @Entity@Table(name = "GOOD")@Where(clause="enabled=1") //Used for logical delete, disabled objects are always hiddenpublic class Good extends AMfgObject implements Serializable { /** serialVersionUID */ 

Hibernate 一对多 保存和修改数据

Student和Sclass表,Student外键cid是Sclass的cid create table sclass( cid varchar(8) primary key, cname varchar(10) )go create table Student ( sid int primary key, sname varchar(10), sno varchar(10), sex varchar(2), email varchar(8), cid varchar(8) foreign ke

Hibernate一对多操作

--------------------siwuxie095 Hibernate 一对多操作 以客户和联系人为例,客户是一,联系人是多 即 一个客户里面有多个联系人,一个联系人只能属于一个客户 注意:这里的客户是公司级的,即 公司,联系人 即 公司里的员工 (一)一对多映射配置 第一步:创建两个实体类,客户和联系人 第二步:让两个实体类之间互相表示 (1)在客户实体类中表示多个联系人 (2)在联系人实体类中表示所属客户 第三步:配置映射关系 「一般一个实体类对应一个映射配置文件」 (1)配置基本

菜鸟学习Hibernate——一对多关系映射

Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生.如图: Hibernate中如何来映射这两个的关系呢? 下面就为大家讲解一下: 1.创建实体类Classes和实体类Student Classes.java package com.bjpowernode.hibernate; import java.util.Set; public class Classes { private int id; private String nam

hibernate 一对多关联关系(详细分析)

在领域模型中, 类与类之间最普遍的关系就是关联关系. 在 UML 中, 关联是有方向的. 以 Customer 和 Order 为例: 一个用户能发出多个订单, 而一个订单只能属于一个客户. 从 Order 到 Customer 的关联是多对一关联; 而从 Customer 到 Order 是一对多关联 单向关联 双向关联 单向 n-1 单向 n-1 关联只需从 n 的一端可以访问 1 的一端 域模型: 从 Order 到 Customer 的多对一单向关联需要在Order 类中定义一个 Cus

Hibernate一对多关系操作

1.创建两个实体类. 一个实体类是商品类,另一个实体类是商品的分类类. 在一对多关系的两个实体中,在编写实体类时必须要遵循以下规则: (1)在一的那一方的实体中,必须要有一个私有的多那一方的实体对象属性,并且提供公有的getter和setter方法. private Integer gid; private String gname; private String gmessage; /** * 在一对多关系中,在一的这一方,必须要有一个多的对象的私有属性 * 别提供共有的getter和sett

Hibernate一对多、多对一关联

一对多.多对一关联:在多方加外键 示例:Group(一方)和User(多方),一个Group可以有多个User,每个User只能属于一个Group   多对一单向关联 在User(多方)中建Group(一方)对象,并添加@ManyToOne注解 1.建Group实体类和User实体类,添加Annotation注解,如下 @Entity @Table(name="_group") //group在MySQL中是关键字,不能直接做表名 public class Group { privat

工作中的程序员如何进阶

前言 你是否觉得自己从学校毕业的时候只做过小玩具一样的程序?走入职场后哪怕没有什么经验也可以把以下这些课外练习走一遍(朋友的抱怨:学校课程总是从理论出发,作业项目都看不出有什么实际作用,不如从工作中的需求出发) 建议: 不要乱买书,不要乱追新技术新名词,基础的东西经过很长时间积累而且还会在未来至少10年通用. 回顾一下历史,看看历史上时间线上技术的发展,你才能明白明天会是什么样. 一定要动手,例子不管多么简单,建议至少自己手敲一遍看看是否理解了里头的细枝末节. 一定要学会思考,思考为什么要这样,

[工作中的设计模式]享元模式模式FlyWeight

一.模式解析 Flyweight在拳击比赛中指最轻量级,即“蝇量级”或“雨量级”,这里选择使用“享元模式”的意译,是因为这样更能反映模式的用意.享元模式是对象的结构模式.享元模式以共享的方式高效地支持大量的细粒度对象. 享元模式:主要为了在创建对象时,对共有对象以缓存的方式进行保存,对外部对象进行单独创建 模式要点: 1.享元模式中的对象分为两部分:共性部分和个性化部分,共性部分就是每个对象都一致的或者多个对象可以共享的部分,个性化部分指差异比较大,每个类均不同的部分 2.共性部分的抽象就是此模