java - 如何在 Spring Data JPA 中保存期间避免选择语句

标签 java spring hibernate spring-data spring-data-jpa

我有一个实体的复合主键(由 3 列组成)。

在复合键的 2 列中,1 列是自动增量,另一列是从另一个实体填充。

当我保存实体时,它执行选择语句,然后执行插入语句。 我想忽略/避免执行 select 语句,因为我知道该实体是唯一的并且只想插入到表中。

我读到实体中有一个带有 @Version 的字段(如 @Version Long version),但是,在这种情况下,我也必须在表上有一列,但我不这样做不想。

执行 select 语句需要花费大量时间,尤其是当我知道我要插入的记录是唯一的时。

[已编辑]

我的实体类是:

@Entity
public class Table implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private TablePK id;

    private String Name;

    private String country;
}

@Embeddable
public class TablePK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private Integer age;
}

日志是:

10:39:57.650 [main] DEBUG org.hibernate.SQL - select 
10:39:57.684 [main] DEBUG org.hibernate.loader.Loader - Done entity load
10:39:57.693 [main] DEBUG o.h.e.i.AbstractSaveEventListener - Generated identifier: 
10:39:57.705 [main] DEBUG o.h.e.t.internal.TransactionImpl - committing
10:39:57.706 [main] DEBUG o.h.e.i.AbstractFlushingEventListener - Processing flush-time cascades
10:39:57.707 [main] DEBUG o.h.e.i.AbstractFlushingEventListener - Dirty checking collections
10:39:57.709 [main] DEBUG o.h.e.i.AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
10:39:57.709 [main] DEBUG o.h.e.i.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
10:39:57.710 [main] DEBUG o.h.internal.util.EntityPrinter - Listing entities:
10:39:57.726 [main] DEBUG org.hibernate.SQL - insert into Table

任何人都可以建议吗?

最佳答案

实体映射设计错误。当您已经想使用自动增量列时,为什么还需要复合标识符?

因此,只需删除 @EmbededId 使用 a simple auto-incremented identifier并将年龄映射为基本属性。

但是还有更多有问题的设计决策,例如:

I read about having a field with @Version (like @Version Long version) in the entity however in that case I will have to have a column in the table as well which I dont want.

@Version注释的原因是prevent lost updates在长时间运行的事务或较弱的隔离级别中。我不确定为什么您认为这与您当前的问题有关。

out of 3 column from composite key, 1 is auto increment and other two are getting populated from another entity.

你说 3 列,但复合 id 只有 2 列。

我建议您阅读this comprehensive JPA and Hibernate tutorial以便您了解 Hibernate 的工作原理以及应该如何使用它。

关于java - 如何在 Spring Data JPA 中保存期间避免选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43652902/

相关文章:

java - hibernate ,保存 map 中的数据

使用表单主体的 Spring MVC Controller 方法映射

spring - Maven 依赖 - org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties 上的 NoSuchMethodError

java - 在 JPA 命名查询中使用 postgres 函数 "lower"时出错

java - OneToOne 和复合主键的 JPA 注释错误

java - 如何将 GWTP 与 ginjector 扩展一起使用?

java - 在过滤器中重定向时停止进一步处理

java - 使用 hibernate native 查询的错误 BigInteger 结果

spring - 如何从 POST 请求中获取响应对象?

mysql - 如何使用hibernate交换数据库中的id