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?

2
  • check this answer stackoverflow.com/questions/15503189/… Commented Jul 14, 2018 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".) Commented Jul 14, 2018 at 21:50

1 Answer 1

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, although introduction of all the new mini-classes (Id-value) caused bunch of new problem to pop up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.