【问题标题】:Mapping one of two classes that implements interface映射实现接口的两个类之一
【发布时间】:2015-07-23 01:11:15
【问题描述】:

类具有可以是两种类类型之一的属性,这就是为什么我尝试创建类类型实现的接口

@Entity
@Table(name = "users")
public class User{  
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userID;
@Column(name="email")
private String email;
@OneToOne(mappedBy = "user")
private Login login;
... getters/setters

@MappedSuperclass
public interface Login {
   User user = new User();
}

@Entity
@Table(name = "user_logins_social")
@IdClass(UserLoginSocialID.class)
public class UserLoginSocial implements Login{      
    @OneToOne
    @JoinColumn(name="uid")
    private User user;
...

@Entity
@Table(name = "user_logins_native")
public class UserLoginNative implements Login{
  @OneToOne
  @JoinColumn(name="uid")
private User user;
...

所以我不能使用目标实体,因为这两个类都可以使用。这是错误堆栈:org.hibernate.AnnotationException:Unknown mappedBy in:model.User.login,引用的属性未知:model.Login.user。请帮帮我

【问题讨论】:

  • 我认为对于这种情况你可能需要Abstarct Class,因为你需要Login 接口中的user 对象的Getter 和setter

标签: java hibernate


【解决方案1】:

无法在接口上映射或查询。

@MappedSuperclass应该可以使用抽象类和类。

请查看:wikihttp://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Interfaces

@MappedSuperclass 
public abstract class User{  
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userID;

@Column(name="email")
private String email;

@OneToOne(mappedBy = "user")
private Login login;

// ... getters/setters

@Entity
@Table(name = "login")
public class Login{      
    @OneToOne
    private User user;
}

@Entity
@Table(name = "user_logins_social")
@IdClass(UserLoginSocialID.class)
public class UserLoginSocial extends User{      
    //...
}

@Entity
@Table(name = "user_logins_native")
public class UserLoginNative extends User{
  //...
}

【讨论】:

  • 如何使登录抽象类而不是接口并将其映射到 POJO 用户。用户有两种记录方式,因此应该将其映射到其中的任何一个,这就是想法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 2023-03-06
  • 2017-05-29
相关资源
最近更新 更多