java - 如何在 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 和limit和offset。
要获得我可以使用的所有元素:
entityManager.createNativeQuery("SELECT name, age, color, weight FROM cats");
在没有entityManager的情况下,我使用了 prepatedStatement:
"SELECT name, age, color, weight FROM cats LIMIT ?,?"
问题:
我怎样才能使用entityManager呢?entityManager有类似preparedStatement
的东西
吗?
解决方案
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();
选择示例(使用TypedQuery
which 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.
推荐阅读
- angular - Angular 9 - 无法实例化循环依赖
- typescript - 如何更改克隆对象中的属性,并且原始对象中的所有属性都没有更改
- c# - 没有 GL.Begin() 的 OpenTK 文本渲染
- php - 从 PC 发送 SMS 消息,就像通过电话发送它们一样
- azure - azure Release 将单个文件复制到 wwwroot 文件夹
- xml - 为 FedEx Web 服务创建 HTTP Post Call
- c# - ASP.NET Core:向所有页面添加背景图像
- python - Pandas:有没有办法检查一个对象是否真的是一个字符串来使用 .str 访问器而不会遇到 AttributeError?
- python - 我想知道为什么它说距离必须小于 27?为什么少于27?27从哪里来?
- javascript - MaterialTextfield 的 Typescript 类型