0

Suppose I have a class MyClass:

public class MyClass {

  @Id
  private int id;

  @???
  private String cityName;

  // getters and setters

}

Now I would like my schema to consist of two tables:

  • MyClassTable: id INT PRIMARY KEY, city INT FOREIGN KEY ON CityTable.id
  • CityTable: id INT PRIMARY KEY, name VARCHAR

Do I have to create a new class for City with two attributes: int Id and String name? Is it possible to accomplish this using only the MyClass class with some special annotation on the cityName?

  • check this answer https://stackoverflow.com/questions/15503189/jpa-annotations-how-to-retrieve-a-single-value-from-a-different-table-than-the – Alexander Polozov Jul 14 '18 at 21:38
  • 1
    Note that this isn't an enum (either in the Java or the database sense). Yes, you'll need to do exactly what you suggested. (And as a note, it's generally better to use the wrapper class `Integer` or `Long`, as the null value more reliably communicates "entity that hasn't been persisted yet".) – chrylis -cautiouslyoptimistic- Jul 14 '18 at 21:50

1 Answers1

1

You should create table 'cities' which is a kind of 'dictionary'. So you can map it to Immutable entity:

@Entity
@Immutable
@Table(name = "cities")
public class City {
    @Id private Integer id;
    private String name;
}

(and populate its data on the database layer).

Then your 'data' entity should have a @ManyToOne reference to the City entity:

@Entity
@Table(name = "my_classes")
public class MyClass {

    @Id
    @GeneratedValue
    private Long id;

    // ...

    @ManyToOne
    private City city;
}

Which will correspond to the following my_classes table (PostgreSQL dialect for example) - pay attention on the foreign key city_id:

create table my_classes (
  id bigint not null constraint my_classes_pkey primary key,
  -- ...
  city_id integer constraint fk_my_classes_cities references cities
)
Cepr0
  • 28,144
  • 8
  • 75
  • 101