java - Spring 动态 JPA 存储库类型

标签 java spring hibernate spring-data-jpa

我需要从 XML 文件中填充大约 30 个表。为此,我想使用 JPA。

现在我有 30 个用 @Entity 注释的类,扫描实体和存储库的配置;

我还有:

@Repository
public interface MyRepository extends JpaRepository<MyEntity1, Long> {
}

和(一些 Controller ):

@Autowired
public MyRepository myRepository;
...
...
MyEntity1 entity = new MyEntity(...);
myRepository.save(entity);

它在一个 @Entity 上运行良好,但我应该为它定义 30 个存储库吗?

我以为我可以做这样的事情:

@Repository
public interface MyRepository<T> extends JpaRepository<T, Long> {
}

然后:

@Autowired
public MyRepository<MyEntity1> myRepository1;
@Autowired
public MyRepository<MyEntity2> myRepository2;

但是这给出了一个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

最佳答案

试试这个方法:

所有实体的基类:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;
}

实体:

@Entity
public class Entity1 extends BaseEntity {

    private String name;
}

@Entity
public class Entity2 extends BaseEntity {

    private String name;
}

一个普通的 repo:

public interface BaseEntityRepo extends JpaRepository<BaseEntity, Long> {
}

用法:

public class BaseEntityRepoTest extends BaseTest {

    @Autowired
    private BaseEntityRepo repo;

    @Test
    public void baseEntityTest() throws Exception {

        BaseEntity entity1 = new Entity1("entity1");
        BaseEntity entity2 = new Entity2("entity2");

        repo.save(entity1);
        repo.save(entity2);

        List<BaseEntity> entities = repo.findAll();
        assertThat(entities).hasSize(2);

        entities.forEach(System.out::println);
    }
}

关于java - Spring 动态 JPA 存储库类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45186236/

相关文章:

java - 本地存储的图像不会显示在 RecyclerView 内的 CardView 中

java - com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure

java - 在Spring Boot Web应用程序中禁用csrf的原因是什么?

java - 使用 hibernate 调用 SQL Server 存储过程

java - 如何删除列表和迭代器中的警告[不是由 @SuppressWarnings ] [在两行代码上应用什么泛型类型]

java - 在 List<Object> 中,如何保留最新条目并删除具有相同字段的先前条目?

java - 发送电子邮件时是否必须提及 SMTP 主机?

java - RabbitMQ 向另一个消费者发出请求

java - 有没有办法在 Spring MVC 测试中不使用 @MockBean?

java - Hibernate 和 InterruptedException