Ignore column if not extist in table Spring Data JPA

Viewed 1658

I have an abtract class like below:

@MappedSuperclass
public  abstract class BaseEntity {

    @Id
    Long id;
    String name;

//getters and setters 
}

and two entity extend BaseEntity

Fist class

@Entity
@Table(name= "table1")
public class TValideB  extends BaseEntity {

 @Column(name = "phone")
 String phone;

}

Second class

@Entity
@Table(name= "table2")
public class TValide extends BaseEntity {

    @Colmun(name = "mail")
    String mail;

}

When i try to save TValide i get error like this non valid column "name"; In my table2 non column exsit for name.

My question is how can i ignore this column and save my entity? Exist an other approaches without delete column name from abstract class?

4 Answers

If you must use base classes, you can create two.

@MappedSuperclass
public  abstract class BaseEntityWithId {

    @Id
    Long id;

//getters and setters 
}

@MappedSuperclass
public  abstract class BaseEntityWithName extends BaseEntityWithId {

  String name;    

//getters and setters 
}

Then you simply have to pick the right one depending on the column layout of the table.

I just add @Column in name with insertable=false, updatable=false edit my abstract class like below:

@MappedSuperclass
public  abstract class BaseEntity {

    @Id
    Long id;
    @Column(name = "name", insertable=false, updatable=false)
    String name;

//getters and setters 
}

This approach avoid me to create a lot of abstract class or rewrite override attributes.

This should solve your problem. In your class that extends BaseEntity, do this for the column that you don't want.

@Entity
@AttributeOverride(name = "name", column = @Column(name = "name", insertable = false, updatable = false)
public class TValide extends BaseEntity {

    @Colmun(name = "mail")
    String mail;

}

Change the way you use abstraction. Create a new abstract class that extends BaseEntity contains fields that are rarely used.

Example:

@MappedSuperclass
public  abstract class BaseEntity {

   @Id
   Long id;

   //getters and setters 
}


@MappedSuperclass
public  abstract class BaseNameEntity extends BaseEntity {

   String name;

   //getters and setters 
}


@Entity
@Table(name= "table1")
public class TValideB  extends BaseNameEntity {

  @Column(name = "phone")
  String phone;

  //getters and setters 
}



@Entity
@Table(name= "table2")
public class TValide extends BaseEntity {

  @Column(name = "mail")
  String mail;

  //getters and setters 
}

By doing this you can configure all your structure.

Related