Search code examples
springhibernatejpa

Spring JPA does not see primary foreign key in repository method


Repository:

public interface CrimeCaseRepository extends JpaRepository<CrimeCase, Integer> {
    boolean existsByCrimeId(int crimeId);
}

CrimeCase:

...
    @Id
    @Column(name = "fk_crime")
    private Integer crimeId;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Crime crime;
...

Crime:

...
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToOne(mappedBy = "crime", fetch = FetchType.LAZY)
    private CrimeCase crimeCase;
...

DB:

CREATE TABLE crime (
  id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
...
);

CREATE TABLE crime_case (
  fk_crime INTEGER PRIMARY KEY,
...
);

Hibernate output:

Hibernate: select cc1_0.crime_id from crime_case cc1_0 where cc1_0.crime_id=? fetch first ? rows only

Exception:

org.postgresql.util.PSQLException: ERROR: column cc1_0.crime_id does not exist

Exception occurs even after renaming crimeId to fkCrime. In this case it must take id from the Crime entity


Solution

  • If you are using @MapsId, then both the entity should share the same primary key. Maybe you should not be using @GeneratedValue(strategy = GenerationType.IDENTITY) to begin with.

    Here is a reference for you

    EDIT

    How is your crime mapped in your database? Why don't you explicitly use something like

    @JoinColumn(name = "crime_id")
    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Crime crime;