4

I am creating a Todo app in Spring Boot and I need to create two tables: Task and Todo(Todo extends Task).

In Task table is a field called description and I would like to prevent that column to be created in Todo table.

How can I do it?

Task(parent):

package com.example.todo.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Task {

    @Id
    private long id;
    private String name;
    private String description;
}

Todo(child):

package com.example.todo.model;

import javax.persistence.Entity;
import javax.persistence.Transient;

@Entity
public class Todo extends Task {

    private boolean isChecked;
}
Jakov
  • 879
  • 2
  • 17
  • 36
  • 4
    Essentially you are indicating that you have two types of Task entities. One with a description and one with a completion (isChecked). If this is the case then you should model it the same way in your code base by creating a new class which inherits from Task and adds the description. – Gerben Jongerius Sep 01 '20 at 13:51

2 Answers2

5

I would suggest you clean up your design because concrete classes inheriting from other concrete classes is (often) a code smell. The proper solution to this is to factor out the common parts of both classes into a (abstract) super class and then add the specific fields to the concrete inheriting classes:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Completable {

    @Id
    private long id;
    private String name;
}
@Entity
public class Task extends Completable {

    private String description;
}
@Entity
public class Todo extends Completable {

    private boolean isChecked;
}

so you have the behaviour grouped in the classes where it belongs and don't have to make sure that one thing contains a description while it shouldn't.

Smutje
  • 17,733
  • 4
  • 24
  • 41
2

What you want cannot be done easily. But you might be trying to solve an issue in the wrong way.

From what I am reading you have a Task entity with has two separate types:

  • one with a checkbox indicating its completion
  • one with an additional description

If this is the case you might want to model the classes the same way. Thus having:

  • A Task entity without the description
  • A Todo entity extending Task with the checkbox
  • A new SummaryTask extending Task with a description field
Gerben Jongerius
  • 719
  • 4
  • 13