您可以为您的 500 个类创建一个基本 abstract 实体,然后为该类创建 一个 repo。 (我认为对于项目中的每个实体,有一个带有id、version 等的BaseEntity 类是一种常见的做法)。
对于简单的 repo 方法(如 save、findAll 等),它可以直接使用(注意 - 实体必须具有相同的 id 类型)。例如:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstarct class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
}
@Entity
public class Entity1 extends BaseEntity {
private String name;
}
@Entity
public class Entity2 extends BaseEntity {
private String name;
}
public interface BaseEntityRepo extends JpaRepository<BaseEntity, Long> {
}
注意BaseEntity 必须有@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 以防止对每个实体使用单表base_entity。并且它们的id 不能相交(参见@GeneratedValue(strategy = GenerationType.SEQUENCE))。
用法:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseEntityRepoTest {
@Autowired private BaseEntityRepo repo;
@Before
public void setUp() throws Exception {
repo.save(asList(
new Entity1("entity1"),
new Entity2("entity2")
));
}
@Test
public void readingTest() throws Exception {
List<BaseEntity> entities = repo.findAll();
assertThat(entities).hasSize(2);
}
}
关于你的第二个问题,你可以使用这种方法:
public interface BaseEntityRepo extends JpaRepository<BaseEntity, Long> {
<T> T findById(Long id, Class<T> type);
}
用法:
@Test
public void findById() {
final Entity1 entity1 = repo.findById(1L, Entity1.class);
final Entity2 entity2 = repo.findById(2L, Entity2.class);
assertThat(entity1).isNotNull();
assertThat(entity2).isNotNull();
}
但是您只能为基类中存在的继承实体的“公共”属性构建 repo 查询方法。要使此方法起作用,您必须将 name 参数移动到 BaseEntity:
<T> List<T> findAllByNameLike(String name, Class<T> type);