2015-05-19 56 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。 –