Amir
Amir

Reputation: 652

Hibernate mapping: ignore a super class field

I have a class A and class B

public class A{
int f1;
int f2;
int f2;
}

public class B extends A{
}

my question is how to ignore a field for example 'f2', in the table mapped to B?

Upvotes: 9

Views: 8997

Answers (2)

Viraj Nalawade
Viraj Nalawade

Reputation: 3227

I will try to answer assuming the edit I have made to your post is approved. In the code below I am ignoring the field f2 from class A i.e. superclass of B using AttributeOverride.

@Entity
@AttributeOverride(name = "f2", column = @Column(name = "f2_col", insertable = false, updatable = false)
public class B extends A{
}

If you want to read about it further, refer to AttributeOverride.

AttributeOverride with insertable = false, updatable = false should help, but it also depends on your inheritance strategy. It just helps making mapped fields inherited from a superclass transient, so that some other subclass can use it but it will be ignored for this particular sub class.

Upvotes: 8

nuno
nuno

Reputation: 1791

If you want to conditionally apply fields to subclasses, maybe you should redesign your classes so that they look like this

public abstract class MyAbstractClass {
    // ...  
}

public class A extends MyAbstractClass {
    int f1;
}

public class B extends MyAbstractClass {
    int f2;
}

Assuming you're applying this to database table mappings with Hibernate, you could use @MappedSuperclass on MyAbstractClass and @Entity on A and B - hope it helps.

Upvotes: 3

Related Questions