Fabian Fasser
Fabian Fasser

Reputation: 1

Problem with JPA ManyToOne Relationship and Foreign Table

I read a lot of questions but haven't found the answer yet.

I've got two different tables WeatherData:

@Entity public class WeatherData implements Serializable {

private static final long serialVersionUID = 14494984498L;

@Id
@GeneratedValue
private long id;

private LocalDateTime localDateTime;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", referencedColumnName = "city_id")
private City city;

and City:

@Entity //@Table(name="city",uniqueConstraints=@UniqueConstraint(columnNames={"zip","city"})) public class City implements Serializable {

private static final long serialVersionUID = 5645010000464665328L;

@Id
@GeneratedValue
@Column(name = "city_id")
private int id;
@Column(name = "zip")
private int zip;
@Column(name = "city")
private String city;

public City() {

}

Now when I try to save the weatherData in the postgresDB it saves always a city for it. But I just want to use the existing entries in the city table:

Example:

CityTable CityTable

WeatherData Table

WeatherData Table

So it should only add entries to the WeatherData Table and use an exisiting city as a foreign key.

Does somebody has an idea?

Thanks

Upvotes: 0

Views: 135

Answers (1)

Amit
Amit

Reputation: 36

If you could share your code how you are creating entities and relating to store data that might help to tell where exactly it is wrong. However : 1. if city entity has id provided which already exists then it will not create any entry into city table. OR 2. You can try with insertable = false attribute of @Column annotation on your city field in WeatherData entity, if there is a use case where city already exists for all cases.

Upvotes: 0

Related Questions