Spring Boot - 从外部 jar 映射实体

ben*_*bjo 5 java spring jar spring-data spring-boot

我在 Spring Boot、Spring Data 和外部 jar 中有实体时遇到了一些问题。任何帮助将不胜感激!

我的 Sprint 数据存储库如下所示:

@Repository
public interface MyFileRepository extends PagingAndSortingRepository<MyFile, Long> {

   @Modifying
   @Transactional
   @Query("Delete from MyFile f where f.created < ?1")
   long deleteOldEntities(Date cutoffDate);
}
Run Code Online (Sandbox Code Playgroud)

我在另一个罐子里的实体完全是这样的:

@Entity
@SequenceGenerator(
   name = "SequenceIdGenerator",
   sequenceName = "SEQ_ID_MY_FILE",
   allocationSize = 20
)
@Table(
   name = "MYFILE_TABLE"
)
public class MyFile extends BaseEntity {

   private long id;  
   private byte[] data;
   [...]

   public MyFile() {}

   @Id
   @Column(
      name = "id",
      nullable = false
   )
   @GeneratedValue(
      generator = "SequenceIdGenerator"
   )
   public long getId() {
      return this.id;
   }

   public void setId(long id) {
      this.id = id;
   }
   [...]
Run Code Online (Sandbox Code Playgroud)

}

BaseEntity 看起来像这样:

@MappedSuperclass
public abstract class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private Date created = null;
    private Date updated = null;

    public BaseEntity() {}

    @Column(
       name = "created"
    )
    @Temporal(TemporalType.TIMESTAMP)
    public Date getCreated() {
        return this.created == null?null:new Date(this.created.getTime());
    }

    public void setCreated(Date created) {
    if(created != null) {
        this.created = new Date(created.getTime());
    }

}
Run Code Online (Sandbox Code Playgroud)

所以,当我尝试运行这段代码时,我得到了一个很长的堆栈跟踪,它基本上以:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: MyFile is not mapped [Delete from MyFile f where f.created < ?1]
Run Code Online (Sandbox Code Playgroud)

我相信这可能与 Spring Boot 配置有关。外部 jar 在任何地方都没有 @SpringBootApplication 。它基本上只是一个装有我所有实体的罐子。

然而,我的应用程序 jar 有这个:

@SpringBootApplication
@EntityScan("myapp.service.dao.entity") --> This is the package where all my entities are located. 
public class CommonApplication {

}
Run Code Online (Sandbox Code Playgroud)

我的错误是什么?

Ben*_*pal 1

要扫描驻留在 jar 中的实体,您必须设置 LocalSessionFactory 的packagesToScan 字段。

@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
    LocalSessionFactoryBean localSessionFactory = new LocalSessionFactoryBean();
    localSessionFactory.setDataSource(dataSource);
    localSessionFactory
            .setPackagesToScan(new String[]{"myapp.service.dao.entity", "com.application.entity"});
    return localSessionFactory;
}
Run Code Online (Sandbox Code Playgroud)