Spring Data Jpa:保存方法仅返回选择,但不执行插入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Data Jpa:保存方法仅返回选择,但不执行插入相关的知识,希望对你有一定的参考价值。

我正在尝试通过使用spring数据JPA保存/更新实体。我有2个实体,它们几乎相似。两个实体都包含组合键。保存方法在一个实体上运行良好。保存方法不适用于其他实体。调用save方法时不会发生插入/更新。它只是返回select语句。

更新/保存ContentCoreNluRepository上的作品

但是只有选择语句从存储库RelationShipTypeRepository中返回

我不确定我要去哪里错。

下面的我的代码。

@SpringBootApplication
public class CdsRmsOutputDbApplication implements CommandLineRunner {

    @Autowired
    RelationShipTypeRepository relationShipTypeRepository;

    @Autowired
    ContentCoreNluRepository contentCoreNluRepository;

    public static void main(String[] args) {
        SpringApplication.run(CdsRmsOutputDbApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        RelationShipType relationShipType = new RelationShipType("TEJA_3059", "alias", "UUCID", "TEJA_3059", "N");

        relationShipTypeRepository.saveAndFlush(relationShipType);

        ContentCoreNlu contentCoreNlu = new ContentCoreNlu(4569l, "Topiccsq", "Analyticscqs", "Analytics", "N",
                BigDecimal.valueOf(0.9999));
        ContentCoreNlu contentCoreNlu1 = new ContentCoreNlu(4569l, "Topiccs", "Analyticscs", "Analytics", "N",
                BigDecimal.valueOf(0.9999));
        ContentCoreNlu contentCoreNlu2 = new ContentCoreNlu(4569l, "Topic", "Analytics", "Analytics", "N",
                BigDecimal.valueOf(0.9999));

        List<ContentCoreNlu> contentList = new ArrayList<>();

        contentList.add(contentCoreNlu);
        contentList.add(contentCoreNlu1);
        contentList.add(contentCoreNlu2);

        contentCoreNluRepository.saveAndFlush(contentCoreNlu);

    }

}

这是我的实体1

@Entity
@Table(name = "content_core_relshp")
@IdClass(RelationShipTypeId.class)
@EntityListeners(AuditingEntityListener.class)
public class RelationShipType {

    @Id
    @Column(name = "universal_content_id")
    private String universalContentId;

    @Id
    @Column(name = "relshp_type")
    private String relationType;

    @Id
    @Column(name = "content_type_id")
    private String contentTypeId;

    @Id
    @Column(name = "content_id")
    private String contentId;

    @Id
    @Column(name = "inact_flg", columnDefinition = "char")
    private String inactFlag;

    @Column(name = "create_ts", updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private java.util.Date createTs;

    @Column(name = "updt_ts")
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private java.util.Date updateTs;

    /**
     * 
     */
    public RelationShipType() {
        super();

    }

    /**
     * @param universalContentId
     * @param relationType
     * @param contentTypeId
     * @param contentId
     * @param inactFlag
     */
    public RelationShipType(String universalContentId, String relationType, String contentTypeId, String contentId,
            String inactFlag) {
        super();
        this.universalContentId = universalContentId;
        this.relationType = relationType;
        this.contentTypeId = contentTypeId;
        this.contentId = contentId;
        this.inactFlag = inactFlag;
    }

    public String getUniversalContentId() {
        return universalContentId;
    }

    public String getRelationType() {
        return relationType;
    }

    public String getContentTypeId() {
        return contentTypeId;
    }

    public String getContentId() {
        return contentId;
    }

    public String getInactFlag() {
        return inactFlag;
    }

    public java.util.Date getCreateTs() {
        return createTs;
    }

    public java.util.Date getUpdateTs() {
        return updateTs;
    }

    @Override
    public String toString() {
        return "RelationShipType [universalContentId=" + universalContentId + ", relationType=" + relationType
                + ", contentTypeId=" + contentTypeId + ", contentId=" + contentId + ", inactFlag=" + inactFlag
                + ", createTs=" + createTs + ", updateTs=" + updateTs + "]";
    }

}

我在变量上有组合键。

public class RelationShipTypeId implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String universalContentId;
    private String relationType;
    private String contentTypeId;
    private String contentId;
    private String inactFlag;

    /**
     * 
     */
    public RelationShipTypeId() {
        super();

    }

    /**
     * @param universalContentId
     * @param relationType
     * @param contentTypeId
     * @param contentId
     * @param inactFlag
     */
    public RelationShipTypeId(String universalContentId, String relationType, String contentTypeId, String contentId,
            String inactFlag) {
        super();
        this.universalContentId = universalContentId;
        this.relationType = relationType;
        this.contentTypeId = contentTypeId;
        this.contentId = contentId;
        this.inactFlag = inactFlag;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((contentId == null) ? 0 : contentId.hashCode());
        result = prime * result + ((contentTypeId == null) ? 0 : contentTypeId.hashCode());
        result = prime * result + ((inactFlag == null) ? 0 : inactFlag.hashCode());
        result = prime * result + ((relationType == null) ? 0 : relationType.hashCode());
        result = prime * result + ((universalContentId == null) ? 0 : universalContentId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RelationShipTypeId other = (RelationShipTypeId) obj;
        if (contentId == null) {
            if (other.contentId != null)
                return false;
        } else if (!contentId.equals(other.contentId))
            return false;
        if (contentTypeId == null) {
            if (other.contentTypeId != null)
                return false;
        } else if (!contentTypeId.equals(other.contentTypeId))
            return false;
        if (inactFlag == null) {
            if (other.inactFlag != null)
                return false;
        } else if (!inactFlag.equals(other.inactFlag))
            return false;
        if (relationType == null) {
            if (other.relationType != null)
                return false;
        } else if (!relationType.equals(other.relationType))
            return false;
        if (universalContentId == null) {
            if (other.universalContentId != null)
                return false;
        } else if (!universalContentId.equals(other.universalContentId))
            return false;
        return true;
    }

}

这是我的第二个实体。

@Entity
@Table(name = "content_core_nlu")
@IdClass(ContentCoreNluId.class)
@EntityListeners(AuditingEntityListener.class)
public class ContentCoreNlu {

    @Id
    @Column(name = "urn_content_core_attrbt")
    private Long urnContentCoreAttributeId;

    @Id
    @Column(name = "nlu_type")
    private String nluType;

    @Id
    @Column(name = "nlu_cd")
    private String nluCd;

    @Column(name = "nlu_name")
    private String nluName;

    @Column(name = "inact_flg", columnDefinition = "char")
    private String inactFlag;

    @Column(name = "nlu_relevance")
    private BigDecimal nluRelevance;

    @Column(name = "create_ts", updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private java.util.Date createTs;

    @Column(name = "updt_ts")
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private java.util.Date updateTs;

    /**
     * 
     */
    public ContentCoreNlu() {
        super();

    }

    /**
     * @param urnContentCoreAttributeId
     * @param nluType
     * @param nluCd
     * @param nluName
     * @param inactFlag
     * @param d
     */
    public ContentCoreNlu(Long urnContentCoreAttributeId, String nluType, String nluCd, String nluName,
            String inactFlag, BigDecimal nluRelevance) {
        super();
        this.urnContentCoreAttributeId = urnContentCoreAttributeId;
        this.nluType = nluType;
        this.nluCd = nluCd;
        this.nluName = nluName;
        this.inactFlag = inactFlag;
        this.nluRelevance = nluRelevance;
    }

    /**
     * @param nluType
     * @param nluCd
     * @param nluName
     * @param inactFlag
     * @param nluRelevance
     */
    public ContentCoreNlu(String nluType, String nluCd, String nluName, String inactFlag, BigDecimal nluRelevance) {
        super();
        this.nluType = nluType;
        this.nluCd = nluCd;
        this.nluName = nluName;
        this.inactFlag = inactFlag;
        this.nluRelevance = nluRelevance;
    }

    public Long getUrnContentCoreAttributeId() {
        return urnContentCoreAttributeId;
    }

    public String getNluType() {
        return nluType;
    }

    public String getNluCd() {
        return nluCd;
    }

    public String getNluName() {
        return nluName;
    }

    public String getInactFlag() {
        return inactFlag;
    }

    public BigDecimal getNluRelevance() {
        return nluRelevance;
    }

    public java.util.Date getCreateTs() {
        return createTs;
    }

    public java.util.Date getUpdateTs() {
        return updateTs;
    }

    @Override
    public String toString() {
        return "ContentCoreNlu [id="  + ", urnContentCoreAttributeId=" + urnContentCoreAttributeId + ", nluType="
                + nluType + ", nluCd=" + nluCd + ", nluName=" + nluName + ", inactFlag=" + inactFlag + ", nluRelevance="
                + nluRelevance + ", createTs=" + createTs + ", updateTs=" + updateTs + "]";
    }

}
public class ContentCoreNluId implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Long urnContentCoreAttributeId;
    private String nluType;
    private String nluCd;
    /**
     * 
     */
    public ContentCoreNluId() {
        super();

    }
    /**
     * @param urnContentCoreAttributeId
     * @param nluType
     * @param nluCd
     */
    public ContentCoreNluId(Long urnContentCoreAttributeId, String nluType, String nluCd) {
        super();
        this.urnContentCoreAttributeId = urnContentCoreAttributeId;
        this.nluType = nluType;
        this.nluCd = nluCd;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((nluCd == null) ? 0 : nluCd.hashCode());
        result = prime * result + ((nluType == null) ? 0 : nluType.hashCode());
        result = prime * result + ((urnContentCoreAttributeId == null) ? 0 : urnContentCoreAttributeId.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ContentCoreNluId other = (ContentCoreNluId) obj;
        if (nluCd == null) {
            if (other.nluCd != null)
                return false;
        } else if (!nluCd.equals(other.nluCd))
            return false;
        if (nluType == null) {
            if (other.nluType != null)
                return false;
        } else if (!nluType.equals(other.nluType))
            return false;
        if (urnContentCoreAttributeId == null) {
            if (other.urnContentCoreAttributeId != null)
                return false;
        } else if (!urnContentCoreAttributeId.equals(other.urnContentCoreAttributeId))
            return false;
        return true;
    }



}

这是我的存储库类。

public interface RelationShipTypeRepository extends JpaRepository<RelationShipType, RelationShipTypeId> {


}
public interface ContentCoreNluRepository extends JpaRepository<ContentCoreNlu, ContentCoreNluId> {

}

这是我的日志

2020-06-11 22:22:26.693  INFO 58052 --- [           main] c.i.c.rms.db.CdsRmsOutputDbApplication   : Starting CdsRmsOutputDbApplication on tejas-mbp.lan with PID 58052 (/Users/teja.kanduri/Documents/JavaPractice/cdsrmsdb/target/classes started by teja.kanduri in /Users/teja.kanduri/Documents/JavaPractice/cdsrmsdb) <br/>
2020-06-11 22:22:26.695  INFO 58052 --- [           main] c.i.c.rms.db.CdsRmsOutputDbApplication   : No active profile set, falling back to default profiles: default <br/>
2020-06-11 22:22:27.160  INFO 58052 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode. <br/>
2020-06-11 22:22:27.200  INFO 58052 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 35ms. Found 2 JPA repository interfaces. <br/>
2020-06-11 22:22:27.707  INFO 58052 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http) <br/>
2020-06-11 22:22:27.717  INFO 58052 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat] <br/>
2020-06-11 22:22:27.717  INFO 58052 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35] <br/>
2020-06-11 22:22:27.801  INFO 58052 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext <br/>
2020-06-11 22:22:27.801  INFO 58052 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1078 ms <br/>
2020-06-11 22:22:28.038  INFO 58052 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor' <br/>
2020-06-11 22:22:28.073  INFO 58052 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default] <br/>
2020-06-11 22:22:28.101  INFO 58052 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.15.Final <br/>
2020-06-11 22:22:28.173  INFO 58052 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final} <br/>
2020-06-11 22:22:28.297  INFO 58052 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting... <br/>
2020-06-11 22:22:29.070  INFO 58052 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed. <br/>
2020-06-11 22:22:29.078  INFO 58052 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.DB2Dialect <br/>
2020-06-11 22:22:29.823  INFO 58052 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] <br/>
2020-06-11 22:22:29.827  INFO 58052 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' <br/>
2020-06-11 22:22:30.114  WARN 58052 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning <br/>
2020-06-11 22:22:30.666  INFO 58052 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '' <br/>
2020-06-11 22:22:30.668  INFO 58052 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories… <br/>
2020-06-11 22:22:30.714  INFO 58052 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized! <br/>
2020-06-11 22:22:30.720  INFO 58052 --- [           main] c.i.c.rms.db.CdsRmsOutputDbApplication   : Started CdsRmsOutputDbApplication in 4.273 seconds (JVM running for 4.59)
Hibernate: select relationsh0_.content_id as content_1_1_0_, relationsh0_.content_type_id as content_2_1_0_, relationsh0_.inact_flg as inact_fl3_1_0_, relationsh0_.relshp_type as relshp_t4_1_0_, relationsh0_.universal_content_id as universa5_1_0_, relationsh0_.create_ts as create_t6_1_0_, relationsh0_.updt_ts as updt_ts7_1_0_ from CDS.content_core_relshp relationsh0_ where relationsh0_.content_id=? and relationsh0_.content_type_id=? and relationsh0_.inact_flg=? and relationsh0_.relshp_type=? and relationsh0_.universal_content_id=?  <br/>
Hibernate: select contentcor0_.nlu_cd as nlu_cd1_0_0_, contentcor0_.nlu_type as nlu_type2_0_0_, contentcor0_.urn_content_core_attrbt as urn_cont3_0_0_, contentcor0_.create_ts as create_t4_0_0_, contentcor0_.inact_flg as inact_fl5_0_0_, contentcor0_.nlu_name as nlu_name6_0_0_, contentcor0_.nlu_relevance as nlu_rele7_0_0_, contentcor0_.updt_ts as updt_ts8_0_0_ from CDS.content_core_nlu contentcor0_ where contentcor0_.nlu_cd=? and contentcor0_.nlu_type=? and contentcor0_.urn_content_core_attrbt=?  <br/>
Hibernate: update CDS.content_core_nlu set inact_flg=?, nlu_name=?, nlu_relevance=?, updt_ts=? where nlu_cd=? and nlu_type=? and urn_content_core_attrbt=? 

这是我的应用程序属性

-spring.data.jpa.repositories.enabled=true
-spring.datasource.url=****
-spring.jpa.properties.hibernate.default_schema=****
-spring.datasource.username=****
-spring.datasource.password=****
-spring.jpa.show-sql=true
-spring.jpa.hibernate.ddl-auto=none
-spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DB2Dialect
-spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
-spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
-spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
答案

当实体被假定为“不是新的”时,Spring数据正在执行休眠合并(请参阅:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-persistence.saving-entites.strategies)。如果未更改实体,则合并不会执行更新。似乎您在DB中已经具有具有相同标识符的relationShipType实体,它等于您尝试更新的实体。

以上是关于Spring Data Jpa:保存方法仅返回选择,但不执行插入的主要内容,如果未能解决你的问题,请参考以下文章

Spring Data JPA:保存嵌套的 OneToMany 子级(具有级联)返回 NULL 父级外部对象

为什么Spring-Data-JPA Async无法正常工作?

Spring Data JPA : 批量增删

Spring Data JPA : 批量增删

Spring Data JPA : 批量增删

Spring Data JPA 参考文档二