Hibernate一对多映射注释问题

时间:2017-05-04 12:45:42

标签: java spring hibernate

我是Hibernate的新手。我有两个表Team(父)和Product(子)与TEAM_ID列作为关系,每个团队将有多个产品,每个产品将有一个团队。我在Team类中创建了@OneToMany映射的实体类,在@ManyToOne类中创建了Product

我需要掩盖以下情景,

  1. 在团队新的时候保存产品和团队
  2. 如果团队已有,则仅保存产品
  3. 当我尝试保存产品时,它会尝试再次保存团队会引发约束错误。 请帮忙。

    Team:
    
    @Entity
    @Table(name = "TEAM")
    public class Team implements Serializable{
    
    private static final long serialVersionUID = 5819170381583611288L;
    
    @Id
    @SequenceGenerator(name="teamIdSeq",sequenceName="team_id_seq",allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="teamIdSeq")
    @Column(name="TEAM_ID", updatable = false, nullable = false, unique = true)
    private int teamId;
    
    @Column(name="NAME", nullable = false, unique = true)
    private String teamName;
    
    @Column(name="DESCRIPTION", nullable = false)
    private String teamDesc;
    
    @Column(name="CONTACTS", nullable = false)
    private String contacts;
    
    @Column(name="APPROVER_NAME", nullable = false)
    private String approverName;
    
    @Column(name="APPROVAL_STATUS", nullable = false)
    private int approvalStatus;
    
    @Temporal(TemporalType.DATE)
    @Column(name="CREATED_ON", nullable = false)
    private Date createdOn;
    
    @Column(name="CREATED_BY", nullable = false)
    private String createdBy;
    
    @Temporal(TemporalType.DATE)
    @Column(name="MODIFIED_ON", nullable = false)
    private Date modifiedOn;
    
    @Column(name="MODIFIED_BY", nullable = false)
    private String modifiedBy;
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy="team", cascade = CascadeType.ALL)
    private Set<Product> products;
    
    //setters and getters   
    }
    
    Product:
    
    @Entity
    @Table(name = "PRODUCT", uniqueConstraints = {@UniqueConstraint(columnNames = {"PRODUCT_ID", "TEAM_ID"})})
    public class Product implements Serializable{
    
    private static final long serialVersionUID = 5819170381583611288L;
    
    @Id
    @SequenceGenerator(name="productIdSeq", sequenceName="product_id_seq",allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="productIdSeq")
    @Column(name="PRODUCT_ID", updatable = false, nullable = false)
    private int productId;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TEAM_ID")
    private Team team;
    
    @Column(name="NAME", nullable = false, unique = true)
    private String productName;
    
    @Column(name="DESCRIPTION", nullable = true)
    private String productDesc;
    
    @Column(name="APPROVER_NAME", nullable = false)
    private String approverName;
    
    @Column(name="APPROVAL_STATUS", nullable = false)
    private int approvalStatus;
    
    @Temporal(TemporalType.DATE)
    @Column(name="CREATED_ON", nullable = false)
    private Date createdOn;
    
    @Column(name="CREATED_BY", nullable = false)
    private String createdBy;
    
    @Temporal(TemporalType.DATE)
    @Column(name="MODIFIED_ON", nullable = false)
    private Date modifiedOn;
    
    @Column(name="MODIFIED_BY", nullable = false)
    private String modifiedBy;
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy="product")
    private Set<Form> forms;
    //setters and getters   
    }
    
    DAO:
    
    @Repository
    @EnableTransactionManagement
    public class KMDBDAOImpl implements KMDBDAO {
    
    @Autowired
    private SessionFactory sessionFactory;
    
    public void addTeam(Team team) {
        Product product = new Product(team, "BMA" + Math.random(), "UI Tool", "test", 
                1, new Date(), "test", new Date(), "test");
        Set<Product> products = new HashSet<Product>();
        products.add(product);
        team.setProducts(products);
        if(getTeam(team.getTeamName()) != null) {
            product.setTeam(getTeam(team.getTeamName()));
            sessionFactory.getCurrentSession().saveOrUpdate(product);
        } else {
            sessionFactory.getCurrentSession().saveOrUpdate(team);
        }
    }
    
    public Team getTeam(String teamName) {
        Query query = sessionFactory.getCurrentSession().createQuery("from Team where teamName = :name");  
        query.setString("name", "teamName");
        return (query.list().size() > 0 ? (Team) query.list().get(0) : null);
    }
    

2 个答案:

答案 0 :(得分:0)

您应该在Team上设置产品列表的唯一时间是Team是新实体。所以:

Set<Product> products = new HashSet<Product>();
products.add(product);
if(getTeam(team.getTeamName()) != null) {
    product.setTeam(getTeam(team.getTeamName()));
    sessionFactory.getCurrentSession().saveOrUpdate(product);
} else {
    team.setProducts(products);
    sessionFactory.getCurrentSession().saveOrUpdate(team);
}

答案 1 :(得分:0)

我给你一些关于一对多关系的示例代码请通过它让我知道如果有问题....我有2个表1.product 2.sku我的条件是,一个产品有很多sku的..

Product.java

@LazyCollection(LazyCollectionOption.FALSE)
    @ElementCollection(targetClass=Product.class)
    @OneToMany(mappedBy="product" , cascade=CascadeType.MERGE)
    private List<Sku> listSkuOrders = new ArrayList<>();

Sku.java

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = PRODUCT_ID , nullable = false)
private Product product;