【问题标题】:EclipseLink entity mapping problem when using property accessor methods使用属性访问器方法时的 EclipseLink 实体映射问题
【发布时间】:2011-07-20 19:47:55
【问题描述】:

鉴于下面的类,有人知道为什么 JPA 的 EclipseLink 实现无法将它们映射到数据库实体吗?返回以下错误:

实体类 [class com.my.entity.Y] 没有指定主键。它应该定义@Id、@EmbeddedId 或@IdClass。如果您使用这些注释中的任何一个定义了 PK,请确保您的实体类层次结构中没有混合访问类型(已注释的字段和属性)。

@Entity
@Access(AccessType.PROPERTY)
public interface Y {

    void setId(Long id);

    @Id
    Long getId();
}

@Entity
public class Z implements Y {

    long id;

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public Long getId() {
        return id;
    }
}

非常感谢

【问题讨论】:

    标签: java jpa eclipselink


    【解决方案1】:

    EclipseLink 确实支持查询和与接口的关系,但目前不在注释中。

    要映射接口,您可以使用 SessionCustomizer。

    public class MyCustomizer implements SessionCustomizer {
        public void customize(Session session) {
          RelationalDescriptor descriptor = new RelationalDescriptor();
          descriptor.setJavaInterface(Y.class);
          descriptor.setAlias("Y");
          session.addDescriptor(descriptor);
        }
    }
    

    映射接口允许查询返回其任何子类的接口,并定义与接口的关系。

    如果通过@VariableOneToOne注解使用接口,则会自动映射。

    【讨论】:

    • 谢谢,这看起来很有希望 - 请详细说明“如果通过 @VariableOneToOne 注释使用接口,它将自动映射”
    • @VariableOneToOne 映射将引用映射到具有多个异构实现者的接口。如果您定义了一个,它会负责为接口注册描述符,因此您不需要使用定制器。
    【解决方案2】:

    感谢链接到this question 的人 - 它帮助我想出了以下问题的解决方案:

        @Entity
        public interface Y {
    
            void setId(Long id);
    
            @Id
            Long getId();
        }
    
       // introduce intermediate abstract class which implements Y
    
        @Entity
        public abstract class X implements Y {
    
        }
    
        // make Z extends X
    
        @Entity
        public class Z  extends X {
    
            // use targetEntity = X.class where required
            // leaving this class still free to use interface Y
    
            long id;
    
            @Override
            public void setId(Long id) {
                this.id = id;
            }
    
            @Override
            public Long getId() {
                return id;
            }
        }
    

    【讨论】:

      【解决方案3】:

      您不能对接口进行注释或查询。只能查询@Entity 类,这些只能放在真实的类上,不能放在接口上。使用@MappedSuperclass 注解进行继承。

      查看这些:http://download.oracle.com/javaee/6/tutorial/doc/bnbqn.html#bnbqp 和 JPA doesn't support interfaces well..implications?

      【讨论】:

        猜你喜欢
        • 2012-08-09
        • 1970-01-01
        • 1970-01-01
        • 2020-07-17
        • 1970-01-01
        • 2012-09-25
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多