Hibernate + Abstract Classes

0

Following as regards my doubts about Hibernate is concerned. Let's say I have a database with the table asignatura .

CREATE TABLE IF NOT EXISTS 'asignatura' (
  'id' int(11) NOT NULL,
  'name' varchar(12) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This class in Java would be abstract:

public abstract class Asignatura{

}

Since this would derive for example, Mathematics, Chemistry ...

public class Matematicas extends Asignatura{

}

My question is, how do I save the objects of Matematicas in the table Asignaturas , is it automatic? or do we have to do something special?

    
asked by Jordi72 17.08.2018 в 16:10
source

1 answer

1

You have a misconception about what it is to keep (persist) objects of a JPA entity in the database. Following the thread of the structure you want to create ...

Asignatura must be a specific class, not abstract.

And "Mathematics" would be an object of that kind, which by persisting it in the database, would be a new record in the Subject table.

The feature class should be something like:

@Entity
@Table(name = "asignatura")
public class Asignatura{
@Id
private int id;
@Column
private String name;
//getters/setters...
}

And create a subject called "Mathematics" would be as follows:

Asignatura nuevaAsignatura = new Asignatura();
nuevaAsignatura.setId(123);
nuevaAsignatura.setNombre("Matemáticas");

To persist this object in the database, the persist() method of the entityManager must be used.

entityManager.persist(nuevaAsignatura);

Internally generate the following SQL code:

INSERT INTO asignatura (id, name)
VALUES (123, 'Matemáticas');

Inserting a new record in the Subject table.

      asignatura
----------------------
| id  |     name     |
----------------------
| 123 |  Matemáticas |
    
answered by 17.08.2018 / 17:23
source