如何在hibernate中保存子对象时获取Parent id

时间:2013-08-29 10:46:58

标签: hibernate

我有两节课如下。

@Entity
@Table(name="KMACLM")
public class ClientTable 
{
    private int RID;
    private String ClientCode,ClientDesc;
    @Id
    @GeneratedValue
    @Column(name="IMACLRID")
    public int getRID() {
        return RID;
    }
    @Column(name="IMACLCLC")
    public String getClientCode() {
        return ClientCode;
    }
    @Column(name="IMACLCLD")
    public String getClientDesc() {
        return ClientDesc;
    }
    public void setRID(int rID) {
        RID = rID;
    }
    public void setClientCode(String clientCode) {
        ClientCode = clientCode;
    }
    public void setClientDesc(String clientDesc) {
        ClientDesc = clientDesc;
    }
}

@Entity
@Table(name = "KMAPLM")
public class PlantTable {
    private Integer RID;
    private String PlantCode,PlantDescription,;
    private ClientTable ClientDetails;
    public void setClientDetails(ClientTable clientDetails) {
        ClientDetails = clientDetails;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "IMACLRID")
    public ClientTable getClientDetails() {
        return ClientDetails;
    }
    @Id
    @GeneratedValue
    @Column(name="IMAPLRID")
    public Integer getRID() {
        return RID;
    }
    @Column(name="UMAPLPTC")
    public String getPlantCode() {
        return PlantCode;
    }
    @Column(name="UMAPLPTD")
    public String getPlantDescription() {
        return PlantDescription;
    }
    public void setRID(Integer rID) {
        RID = rID;
    }
    public void setPlantCode(String plantCode) {
        PlantCode = plantCode;
    }
    public void setPlantDescription(String plantDescription) {
        PlantDescription = plantDescription;
    }
}

这是struts行动。

Session s=null;
 Transaction t=null;    
try{

s=Hibernate_Common.getsessionfact().openSession();
t=s.beginTransaction();
ClientTable dd=new ClientTable();
dd.setClientCode(getClient());  //here i am setting client (Parent Element)

PlantTable Planttbobj=new PlantTable();
Planttbobj.setPlantCode(getPlantCode());
Planttbobj.setPlantDescription(getPlantDescription());
Planttbobj.setClientDetails(dd);
s.save(Planttbobj);
    t.commit();
    s.close();
}catch(Exception e)
{
    t.rollback();
    s.close();
     e.printStackTrace();
}

我从jsp获取值并保存在数据库中。

每次在数据库中插入子元素和父元素时,我都会尝试保存对象。

首次插入

IMACLRID    IMACLCLC    IMACLCLD
4           600         chennai

IMAPLRID    UMAPLPTC    UMAPLPTD    IMACLRID
3       7023        madurai     4

第二次插入

IMACLRID    IMACLCLC    IMACLCLD
4       600     chennai
5       600     chennai

IMAPLRID    UMAPLPTC    UMAPLPTD    IMACLRID
3       7023        madurai     4
4       7024        theni       5

每当我试图插入一个孩子父母也插入

在父表中插入重复值。请帮助我!!!

0 个答案:

没有答案