Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Prevent persisting field declared in superclass

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;
}
like image 656
Jakov Avatar asked Mar 02 '23 02:03

Jakov


2 Answers

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.

like image 145
Smutje Avatar answered Mar 05 '23 06:03

Smutje


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
like image 31
Gerben Jongerius Avatar answered Mar 05 '23 05:03

Gerben Jongerius