I am currently working with Spring Data JPA, specifically Postgres. Our database is highly Normalized. In some scenarios we have some tables that contains static data. In that case if I am going to insert into table address for example and table address_type contains the static data, I would need to insert the Primary Key of table address_type in a column of table address, to make a Foreign Key reference from table address to table address_type(static data).
Example:
Database Code
create table address_type(
id Serial Primary Key,
type char(3),
description (100)
);
insert into address_type(id, type, description) values(1, 'PRIMARY', 'Primary description');
insert into address_type(id, type, description) values(2, 'SECONDARY', 'Secondary description');
Relation (1 - N)
create table address(
id Serial Primary Key,
address varchar(50) not null,
address_type_id integer references address_type(id)
);
insert into address(id, address, address_type) values(1, 'address somewhere 1', 1);
insert into address(id, address, address_type) values(2, 'address somewhere 2', 1);
insert into address(id, address, address_type) values(3, 'address somewhere 3', 2);
Spring Data JPA Code
@Table(name = "address_type")
public class AddressType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "type")
private String type;
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "addressType")
private Address address;
// Getters and Setters (Lombok)
}
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "type")
private String address;
@Column(name = "address_type_id")
@JoinColumn(---> logic?????????? <-----)
@ManyToOne(---> logic?????????? <-----)
private AddressType addressType;
// Getters and Setters (Lombok)
}
I guess my question is how should I need to setup the logic inside the @JoinColumn and @ManyToOne annotations in the Address entity?
P.D. The Insert should only happen in table address, Spring Data should only read from table address_type to get the foreign key to be stored in the address table.