【问题标题】:CrudRepository not returning database elements from APICrudRepository 未从 API 返回数据库元素
【发布时间】:2017-04-30 05:31:04
【问题描述】:

我正在构建一个 Spring Boot 应用程序,它将数据填充到休眠数据库中。我已经编写了从外部 API 提取数据并将它们加载到我的数据库中的 DAO(这工作正常)。但是,我想使用CrudRepository 为我的数据生成 REST API。所以我创建了一个扩展它的NewsItemRepository

public interface NewsItemRepository extends CrudRepository<NewsItem, Long>

我的NewsItemDao 是对数据库进行持久化和从数据库获取的功能:

@Override
public List<NewsItem> fetchAllNewsItems() {

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<NewsItem> criteria = builder.createQuery(NewsItem.class);
    Root<NewsItem> newsItemRoot = criteria.from(NewsItem.class);
    criteria.orderBy(builder.desc(newsItemRoot.get("date")));

    List<NewsItem> newsItemList = entityManager.createQuery(criteria).getResultList();

    entityManager.close();

    return newsItemList;
}

    @Override
public void save(NewsItem newsItem) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(newsItem);
    entityManager.getTransaction().commit();
    entityManager.close();
}

API 功能似乎正在运行 (localhost:8080/api/v1):

{
  "_links" : {
    "newsItems" : {
      "href" : "http://localhost:8080/api/v1/newsItems"
    },
    "profile" : {
      "href" : "http://localhost:8080/api/v1/profile"
    }
  }
}

但是,在 localhost:8080/api/v1/newsItems 中没有填充 newsItems:

{
  "_embedded" : {
    "newsItems" : [ ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/v1/newsItems"
    },
    "profile" : {
      "href" : "http://localhost:8080/api/v1/profile/newsItems"
    }
  }
}

我能够从数据库中访问 newsItems 并显示它们。但我想让 API 功能正常工作,但我不知道我缺少什么才能让它工作。我确实注意到我的数据库中添加了两个额外的空白表,但我没有在任何地方指出发生这种情况/指定它们的名称。 news_itemnews_source(我也有一个新闻源实体)。填充的表是newsitemnewssource

如果需要任何进一步的信息来提供答案,请告诉我。

【问题讨论】:

  • 似乎您对 Dao 层中的每个方法都使用了单独的 entityManager,这是一种不好的做法。请改用共享的entityManager。回到您的问题,post 可能会为您的问题提供解决方案。

标签: java spring hibernate rest jpa


【解决方案1】:

您在 DB 中获取新表的原因是休眠默认情况下会将您的 POJO 实体映射到其非限定类名等价物,即 NewsItem 到 news_item,您可能已经在您的 persistence.xml 中指定

hibernate.hbm2ddl.auto = create-drop |更新

有两种解决方案 1.您使用hibernate默认使用的约定,并将您的表重命名为news_item和news_source 2.可以在POJO类的顶部指定表名

@Entity
@Table(name="newsitem")
public class NewsItem implements Serializable {}

【讨论】:

    猜你喜欢
    • 2015-03-14
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2021-12-13
    • 2015-04-03
    • 2014-11-02
    • 1970-01-01
    • 2018-04-26
    相关资源
    最近更新 更多