2015-05-19 59 views
1

使用休眠和我無法保存實例。休眠不查找屬性值

我有以下DB結構:

Item 
- id 
- attributeId 
- other stuff 

Attribute 
    - id 
    - code 
    - name 

假設屬性表有類似的條目:

1 T Type1 
2 R RType 
3 G GType 

這裏是註釋該類:

Class Attribute { 
    @Id 
    @Column(name = "ID") 
    protected long id; 

    @Column(name = "CODE", updatable = false) 
    protected String code; 

    @Column(name = "NAME", updatable = false) 
    protected String name; 
} 

所以我希望能夠創建一個新的Item類併爲其賦予一個帶有代碼和名稱fil的Attribute類帶領出去。讓hibernate查找屬性的id,然後將該id插入到Item的attributeId列中。

這些都是我的註解項目:

@Id 
@GeneratedValue(strategy = GenerationType.SEQUENCE, 
       generator = "item_seq") 
@SequenceGenerator(name = "item_seq", sequenceName = "ITEM_SEQ", 
        allocationSize = 1) 
@Column(name = "ID") 
protected long id; 

@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) 
@JoinColumn(name="ATTRIBUTE_ID", insertable = true, updatable = true) 
private Attribute attribute; 

我怎麼可以給項目類屬性類,充滿了代碼和說明,並將它查找id爲屬性並將其分配項目?

回答

0

你不需要明確設置屬性ID,Hibernate會爲你做到這一點。您只需要將Attribute(不管是新實例還是現有實例)的實例設置爲Item實例,然後保存該項目。像這樣的東西

Item item = new Item(); 
// if you want to use an existing attribute, fetch it from some DAO by id 
Attribute att = session.get(Attribute.class, someId); 
item.setAttribute(att); 
// save item 
session.save(item); 
+0

這是關鍵,我不想得到一個get。我希望在保存發生時進行查找。 –

+0

好的,使用'session.load()'而不是'session.get()'。它只會持有對實體的引用,而不會進行select to db。 –