如何为所有实体设置JpaRepository接口的通用实现?

时间:2016-12-14 09:15:12

标签: java hibernate spring-data

这是我的项目结构:
@MappedSuperclass基类:

@MappedSuperclass
public class BaseClass {

   @Id
   @GeneratedValue(strategy = GenerationType.TABLE)
   private long id;
   //getter and setter
}

扩展基类的@Entity

@Entity
public class Person extends BaseClass {

  private String regisNumber;
  private String name;
  private int hPerWeek;

  /**
   * @param regisNumber
   * @param name
   * @param hPerWeek
   */
  public Person(String regisNumber, String name, int hPerWeek) {
      super();
      this.regisNumber = regisNumber;
      this.name = name;
      this.hPerWeek = hPerWeek;
  }
  //getters and setters
}

通用DAO:

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

在我的测试中,创建Person可以正常工作:

@Autowired
IDao<Person> dao;

@Test
public void whenPersonEntityIsCreated_thenNoExceptions() {
    Person person = new Person("mkd90ii", "manu", 24);      
    dao.save(person);

}

然而,尝试获得Person

@Test
public void whenPersonEntityIsUpdated_thenNoExceptions() {
    Person person = dao.getOne(Long.valueOf(32768));
    System.out.println(person.toString());
    //Updating person...

}

生成了这个错误:

   org.springframework.dao.InvalidDataAccessApiUsageException: Unknown   entity: com.bockmoi.entities.BaseClass;   
     nested exception is java.lang.IllegalArgumentException: Unknown  entity: com.bockmoi.entities.BaseClass

我明白这是因为BaseClass不是javax.persistence.Entity,但为什么创作有效而不是阅读?

有人可以解释一下为什么会发生这种情况以及如何克服这个问题? 对我来说这是一种死路一条 感谢

0 个答案:

没有答案