【问题标题】:Custom methods don't EVER get callled, even when annotations are on the method?自定义方法永远不会被调用,即使方法上有注释?
【发布时间】:2011-07-14 23:04:09
【问题描述】:

在我的实体对象中,我将所有 JPA 注释放在字段上。它们与 Project Lombok 配合得很好,它为我生成了所有的 getter 和 setter,大大简化了我的代码。

编辑:

当我将注释向下移动到方法时,这似乎也会发生

@OneToMany(targetEntity = ChannelDAOHb.class, mappedBy = "server", orphanRemoval = true)
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE})
public Set<ChannelDAO> getChannels() {
    System.out.println("Getting some channels");
    ...
}

getChannels().add(new Channel("someChannel")); //Nothing printed here

但是,我的 OneToMany 关联字段之一的自定义 getter 似乎没有被调用。甚至像这样具有破坏性的东西

public Set<ChannelDAO> getChannels() {
    throw new RuntimeException("Take that, Hibernate");
}

getChannels().add(new Channel("someChannel"));

永远不会抛出该异常。

这里发生了什么?为什么我的吸气剂没有被调用?

【问题讨论】:

  • @Marcelo 不,我的字段不公开

标签: java hibernate


【解决方案1】:

Hibernate 默认使用反射。方法仅适用于您自己的 API。这减少了设置持久层所需的脚手架。

【讨论】:

  • 不,我的意思是从我自己的代码中调用getChannels() 并不会消除该异常。我应该在问题中澄清这一点
  • @TheLQ 好的,Hibernate 实际上创建了继承您的实体的代理类,以便能够处理管理关系的惰性方法,并且您的 getChannels() 方法将被延迟加载行为覆盖。跨度>
  • @Marcelo 太棒了...这是否意味着我现在必须将所有 JPA 注释移动到 getter?
  • @TheLQ 不,尝试将您的关系设置为 Fetch.Eager,看看这种行为是否会改变。
  • @TheLQ、@Marcelo、@Petro:我使用 Hibernate 3.6.5.Final 在 github 上创建了一个示例项目,它表明在代理上调用 getter 会执行 getter 中的实际代码。如果你有 git 和 maven,可以试试看:“git clone git://github.com/zzantozz/testbed.git tmp”“cd tmp”“mvn compile exec:java -D exec.mainClass=rds.testbed.hibernateproxies.Main -pl hibernate-proxies
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多