如何在Spring Boot Application中使用JPA删除/获取列表

时间:2019-02-23 02:54:15

标签: java spring hibernate spring-boot jpa

我有一个 实体

@Override
public void delete(Cat cat) {
    entityManager.remove(cat);
}

1 。我需要使用 EntityManager 从数据库中 删除

Map<String, Cat>

问题:我有一个entityManager.createNativeQuery("SELECT name, age, color, weight FROM cats");,其中包含所有这些元素。我从地图 IllegalArgumentException ->“删除分离的实例com.entities.Cat#cats”中按名称获取。

问题 :我如何 不从密钥中获取

2 。我需要使用 limit offset 的getList。

获取全部 ,我可以使用的元素:
 "SELECT name, age, color, weight FROM cats LIMIT ?,?"

没有 entityManager ,我将 prepatedStatement 用于:

{{1}}

问题
我该如何使用 entityManager
entityManager 是否具有类似 preparedStatement 的内容?

2 个答案:

答案 0 :(得分:2)

通过EntityManager,您可以使用Query对象。它为您提供了多种构建查询的方法,您可以在Docs中看到它们。

从那里,您可以使用Query来执行选择或对数据库执行更新。

更新示例:

//:id is a parameter you can set
Query query = entityManager.createQuery("delete from Entity e where e.id = :id");
query = query.setParameter("id", id);
query.executeUpdate();

选择示例(使用实现TypedQuery的{​​{1}}:

Query

您可以像这样确定极限和偏移量:

String sql = "select e from Entity e";
TypedQuery<Entity> query = entityManager.createQuery(sql, Entity.class);
System.out.println(query.getResultList());

如果您手边有实体,则可以可以(并且应该)使用query = query.setFirstResult(offset); query = query.setMaxResults(limit); EntityManager将其删除。之所以收到该错误,是因为您的实体已分离-即您的remove()不知道其存在。

要将实体“附加”到您的经理,您可以使用EntityManager。但是,如果所述实体在数据库中不存在,则将其插入,如果该实体存在但与您的对象具有不同的字段,则将对其进行更新。

merge()

要首次插入实体,您还可以使用public void delete(Cat cat) { if(!entityManager.contains(cat)) { entityManager.merge(cat); } entityManager.remove(cat); } 。有关persist()merge()之间的区别,请参见this

答案 1 :(得分:1)

  1. 如果您需要使用EntityManager,则只需使用引用:

    entityManager.remove(entityManager.getReference(Cat.class, id));
    

    这样,将不会从数据库中获取实体,但是会将其删除。

    使用查询也是一种选择:

    Query query = entityManager.createQuery("delete from Entity e where e = :entity");
    query = query.setParameter("entity", entity);
    query.executeUpdate();
    
  2. 您可以使用Query创建EntityManager#createQuery。然后设置参数:firstResultmaxResults

    query.setFirstResult(10).setMaxResults(20);
    

    这将从10日开始占用20个实体。