首页 > 解决方案 > 如何在 Spring Boot 应用程序中使用 JPA 删除/getList

问题描述

我有一个实体

@Entity
@Table(name ="cats")
public class Cat {
    @Id
    @Column(name="name")
    private String name;

    @Column(name="age")
    private int age;

    @Column(name="color")
    private String color;

    @Column(name="weight")
    private int weigth;
  ..
}

1 . 我需要使用EntityManager从数据库中删除它:

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

问题:我有一个Map<String, Cat>包含所有这些元素的。我从地图IllegalArgumentException ->“删除分离的实例 com.entities.Cat#cats”中按名称获取它。

问题:如果不通过密钥从数据库中获取,我怎么能做到这一点

2 . 我需要 getList 和limitoffset

获得我可以使用的所有元素:
entityManager.createNativeQuery("SELECT name, age, color, weight FROM cats");

在没有entityManager的情况下,我使用了 prepatedStatement

"SELECT name, age, color, weight FROM cats LIMIT ?,?"

问题
我怎样才能使用entityManager呢?entityManager有类似preparedStatement
的东西 吗?

标签: javaspringspring-bootspring-data-jpajpql

解决方案


EntityManager你可以使用对象Query。它为您提供了几种不同的方法来构建您的查询,您可以在Docs中看到这些方法。

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

更新示例:

//: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();

选择示例(使用TypedQuerywhich implements 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);

If you have an entity at hand you can (and should) delete it using your EntityManager with remove(). You're getting that error because your entity is detached - that is, your EntityManager isn't aware of its existence.

To "attach" entities to your manager you can use merge(). However, if said entity doesn't exist in the database it will be inserted, and if it exists but has different fields from your object it will be updated.

public void delete(Cat cat) {
    if(!entityManager.contains(cat)) {
        entityManager.merge(cat);
    }

    entityManager.remove(cat);
}

To insert entities for the first time you can also use persist(). For the differences between merge() and persist(), see this.


推荐阅读