抽象类继承在Spring Boot中

huangapple go评论67阅读模式
英文:

Abstract class inheritance in springboot

问题

我对抽象类有些困惑,希望能得到帮助。

我有以下的类:

 public abstract class AbstractUser{
    private String username;
    private String password;
}

然后我有这个类:

@Entity
public class Company extends AbstractUser{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String company_name
}

现在当我启动应用程序并检查 h2-console 时,Company 表只有 id 和 company_name 列,没有抽象类的变量。有办法让它包含所有的变量吗?

提前谢谢。

英文:

I am a bit confused in regards to abstract classes and help would be great.

I have a the following classes

 public abstract class AbstractUser{
    private String username;
    private String password;
}

And then I have this class

@Entity
public class Company extends AbstractUser{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String company_name
}

Now when I launch the application and I check the h2-console, the table Company only has the id and company_name. not the abstract classes variables. Is there a way to make it so it gets all the variables?

thank you in advance

答案1

得分: 0

为了解决这个问题,您需要在抽象类上使用JPA注解。这与Spring Boot无关,而是与JPA有关。

您可以在抽象类上应用@MappedSuperclass注解,这应该可以解决这个问题。了解更多信息:继承超类属性

英文:

To resolve this, you will need JPA annotation on your abstract class. This is not specific to Spring Boot, it's JPA thing.

You can apply @MappedSuperclass on your abstract class and that should resolve this issue. Find More: [Inherit Super Class Properties](https://vladmihalcea.com/how-to-inherit-properties-from-a-base-class-entity-using-mappedsuperclass-with-jpa-and-hibernate/ "Inherit Super Class Properties")

答案2

得分: 0

你可以在AbstractUser上使用@MappedSuperclass Jpa注解,还可以考虑将id属性移到抽象类中。

@MappedSuperclass
public abstract class AbstractUser{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;
}
英文:

You can use @MappedSuperclass Jpa annotation on the AbstractUser, Also consider moving the id attribute to the abstract class.

@MappedSuperclass
public abstract class AbstractUser{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;
}

huangapple
  • 本文由 发表于 2020年9月10日 11:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63822336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定