Good day, here is problem: CrudRepository returns wrong Id for entities.
Here is base JPA user entity:
@Data
@Entity(name = "user")
@EqualsAndHashCode(exclude = {"roles", "password", "data"})
@ToString(exclude = {"roles", "password", "data"})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
private SomeData data;
...
There is a relation one-to-one to some data entity.
@Data
@Entity(name = "some_data")
@TypeDefs({
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
@ToString(exclude = {"user", "views", "biData"})
@EqualsAndHashCode(exclude = {"user", "views", "biData"})
public class SomeData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
@MapsId
private User user;
...
And there is crud repository:
@Repository
public interface SomeDataRepository extends CrudRepository<SomeData, Long> {
Optional<SomeData> findByUserId(Long userId);
}
Method findUserById returns correct SomeData entity from DB, but this entity has the same ID with userId... And because of it I can't do other activities (insert or update on table "public_view" violates foreign key constraint "fk_view_to_some_data")
It's quite strange.
The problem could be because you use the @MapsId
annotation. Here's what the value of the annotation does, as per Javadoc:
The name of the attribute within the composite key to which the relationship attribute corresponds. If not supplied, the relationship maps the entity's primary key.
You could try to set a specific value to your annotation, or map differently your one-to-one relationship. For example, use the @JoinColumn
annotation in your SomeData
class:
// ... your annotations ...
public class SomeData {
// ... your other fields ...
@OneToOne
@JoinColumn(name = "some_data_id", referencedColumnName = "id")
private User user;
}
Here are some alternatives that you could use: https://www.baeldung.com/jpa-one-to-one