2012-04-25 79 views
1

这里是我的实体的片断(它也有哈希码,等于创造了它们在Java休眠加载复合键的对象总是返回

@Entity 
@Table(name = "media_tspec_external_registry") 
public class Registry implements Serializable { 


public Registry() { 
    //for hibernate :D 
} 



public Registry(String show, String protocol, String externalEndpoint, String userURI, String version) { 
    super(); 
    this.show = show; 
    this.protocol = protocol; 
    this.externalEndpoint = externalEndpoint; 
    this.userURI = userURI; 
    this.version = version; 
} 




@Id 
@Column(name = "show", nullable = false) 
private String show; 

@Id 
@Column(name = "protocol", nullable = false) 
private String protocol; 

@Column(name = "external_endpoint", nullable = true) 
private String externalEndpoint; 

这里生成的默认的是我的方法,试图加载不存在,基于这些键值

Registry reg = new Registry("invalid", "idvalue", null, null, null); 
    Registry reg2 = null; 
    try { 

     reg2 = (Registry) session.load(Registry.class, reg); 
      } catch (HibernateException e) { 
     throw new UserException("A registry entry does not exist for this show: " + show + " and protocol: " + protocol); 
     } 

它不会抛出异常,并REG2现在设置为一个注册表对象设置为空的所有字段的实体。

我也注意到负载甚至不会加载现有的实体。

但是如果我用得到,而不是它工作正常(用于装载不存在的对象返回null的有效对象)

reg2 = (Registry) session.get(Registry.class, reg); 

任何解释,将不胜感激。

感谢

+0

奇怪。注册表同时是实体和组合键吗? – 2012-04-25 17:58:16

+0

@PiotrKochański根据[hibnate文档](http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-identifier)节2.2.3.2.2。我把那意味着实体本身是序列化的标识符(类似于idclass或嵌入ID) – 2012-04-25 18:16:36

+0

看回答问题http://stackoverflow.com/q/608947/971040 它可以引导你在正确的办法。 – viktor 2012-04-25 21:20:52

回答

1

这是预期的行为。 session.load是为了得到一个可以用来满足引用的对象,例如

User u = new User(); 
u.setRole((Role)session.load(Role.class, 5)); 
session.save(u); 

负载不会产生往返。如果没有对可用对象的引用,它将创建一个proxyobject,或者在您的情况下将回收您的组合键对象,并依赖于该实体的存在,因为它不会询问数据库是否如此。