Sadath
Sadath

Reputation: 21

Select a default Entity when two or more Entities with same name exist - Spring Boot, Spring Data JPA,

I'm using spring data jpa for persistence. Is there a way where one entity can be marked as default if more than one entity exists with the same name. Something like @Primary annotation used to resolve multiple bean dependencies problem

@Entity(name = "ORGANIZATION")
@Table(name = "ORGANIZATION")
public class DefaultOrganization {
     ***
}

@Entity(name = "ORGANIZATION")
@Table(name = "ORGANIZATION")
public class Organization {
     ***
}

Updated

Let me make it clearer. I'm using spring-boot @EntityScan annotation which does the package scanning, if two entities with same name are found in two different packages then there should be a way in which only one entity gets selected and registered whereas the other is rejected. As far as entity names are concerned even I'm aware that no two entities can have same name. I'm asking this in context of spring-boot and spring-data-jpa

@Entity(name = "ORGANIZATION")
@Table(name = "ORGANIZATION")
@PrimaryEntity
public class DefaultOrganization {
     ***
}

@Entity(name = "ORGANIZATION")
@Table(name = "ORGANIZATION")
public class Organization {
     ***
}

Since DefaultOrganization is marked with @PrimaryEntity, DefaultOrganization should be selected by @EntityScan whereas Organization should be rejected.

Note : @PrimaryEntity is non JPA Standard custom annotation that can be processed by spring-boot @EntityScan

Upvotes: 2

Views: 13848

Answers (1)

Buddhika Ariyaratne
Buddhika Ariyaratne

Reputation: 2433

It is not possible to have duplicate name for two different Entities for one Project even the entities reside in two different packages.

Reference 1

Entity Class Names

By default, the entity name is the unqualified name of the entity class (i.e. the short class name excluding the package name). A different entity name can be set explicitly by using the name attribute of the Entity annotation:

@Entity(name="MyName")
public class MyEntity {

}

Entity names must be unique. When two entity classes in different packages share the same class name, explicit entity name setting is required to avoid collision.

Upvotes: 11

Related Questions