Search code examples
javahibernatejpajava-ee-6hibernate-search

Create separate hibernate search indexes for each subclass


I just started playing around with hibernate search. How can I solve the following problem.

All my java entities where inherited from a superclass:

@SuppressWarnings("rawtypes")
@MappedSuperclass
@Indexed
public abstract class BaseEntity{

        private Integer id;
   private Integer jpaVersion;
   private Date creaDate;
   private Date modDate;
   private String creaUser;
   private String modUser;


        @Id
   @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0)
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   public Integer getId() {
     return this.id;
   }

   public void setId(Integer id) {
     this.id = id;
   }   
   .....

For example I have to (there are more) subclasses:

@Entity
@Indexed
@Table(name = "BASE_PERSON", schema = "MYSCHEMA")
public class Person extends extends BaseEntity{

private String firstName;
private String lastName;
....
....

@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
  @Column(name = "LASTNAME", nullable = false, length = 50)
  @NotNull
  @Size(max=50)
  public String getLastName() {
    return this.lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
  @Column(name = "FIRSTNAME", length = 50)
  @Size(max=50)
  public String getFirstName() {
    return this.firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

and a second one:

@Entity
@Indexed
@Table(name = "BASE_USER", schema = "MYSCHEMA")
public class User extends extends BaseEntity{

private String userName;
....
....

@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
  @Column(name = "USERNAME", nullable = false, length = 50)
  @NotNull
  @Size(max=50)
  public String getUserName() {
    return this.userName;
  }

  public void setUserName(String lastName) {
    this.UserName = UserName;
  }

  ....

After running the code for creating the whole index, I got three indexes. One more than I expected. The indexes are: BaseEntity, Person and User. But all Persons and Useres ares stored in the index BaseEntity and not in their own index. Is there a way to change this, so that all persons are in the index person and all users are in the index users?

Or is this the common behaviour of hibernate search?

Thanks and Regards LStrike


Solution

  • You'll want to remove the @Indexed from the BaseEntity, you only need that annotation on the subclasses. You can still annotate properties in BaseEntity with @Field to make them appear in the subclass indexes.