Search code examples
javahibernatehibernate-mappingspring-data-jpa

Cannot override default id column spring data JPA


I recently refactored our database schema to have the id columns in each of our tables to be in the format "tableName" + ID, IE "SettingsID" instead of just "id" across all tables. Now my spring-data backend is breaking when I try to fetch anything from one of those tables. It complains that there is an "invalid column name 'id'". I assume what I need to do is map my new name of the ID column to what spring data wants to be the id column, but I havent been successful so far.

I think the only configuration needed would happen within my entity object. Here is my Settings.java entity object class:

@Entity
@Table(name = Settings.TABLE_NAME)
public class Settings extends AbstractPersistable<Long> {
public static final String TABLE_NAME = "SETTINGS";

@AttributeOverride(name = "id", column = @Column(name="settingsID"))
private long settingsID;

@Column(name = "CUSTOMERID")
private String customerID;

@Column(name = "MERCHANTID")
private String merchantID;
...
....
}

And just in case it matters, (Which I don't think it does) here is the function I am calling when this error is thrown:

@Repository
public interface SettingsDAO extends CrudRepository<Settings, Long> {


/**
 * Finds the entry in the Settings table for a given customerID
 * @param customerID   The customerID to search for
 * @return             The settings object for the given customer ID
 */
Settings findOneByCustomerID(String customerID);

}

The error I get is (beside from the generic hibernate error saying it cant extract the resultset) is

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'id'.

Solution

  • After checking out this post, I realized that I wasn't supposed to add the @AttributeOverride annotation on the field, but the class itself. That way, spring data will not try to double map the id field. My new entity object looks like this:

    @Entity
    @Table(name = Settings.TABLE_NAME)
    @AttributeOverride(name="id", column=@Column(name="SETTINGSID"))
    public class Settings extends AbstractPersistable<Long> {
    public static final String TABLE_NAME = "SETTINGS";
    
    
    @Column(name = "CUSTOMERID")
    private String customerID;
    
    @Column(name = "MERCHANTID")
    private String merchantID;
    ...
    

    Notice there is no field for id now.