Hibernate and Inheritance - need to add one additional column (Spring Boot)

173 Views Asked by At

I have table A:

@Entity
@Table(name = "A")
public class A{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "message_id")
    private Message;
}

I have a table Message:

@Entity
@Table(name="message")
@Getter
@Setter
public class Message{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_id", foreignKey = @ForeignKey(name = "FK_account_to_message"))
    private Account account; //and then search by Account.id
}

In my service I get all A objects by:

List<A> aObjects = ARepository.findByMessage_Account_Id(user.getId())

So I want to get all A objects which have such Message fields that Message fields have such Account fields that Account.id == user.getId()

Now I have additional type of A entity - without any relation to Message because now object A can be created by uploading an Excel file (reading data from a file and saving in database, so in this case we don't have Message data that can be added in Message column). So I have to store new A objects in A table but with empty column Message BUT with additional column -> user_id -> currently that's the parameter to find all A objects (ARepository.findByMessage_Account_Id(user.getId())) The question is how/where to store A objects that differ in Message column (empty, no relationship to Message table).

I thought about Single Table Inheritance with Discriminator value but in this case when I want to find all A objects by user_id I would have to prepare one bigger select like: get all A objects from A where A.Message.Account.id = user_id or A.user_id = user_id.

Is it a good approach? Or maybe should I use something different?

0

There are 0 best solutions below