Java Spring JPA插入数据至

huangapple go评论76阅读模式
英文:

Java Spring JPA insert into

问题

请帮助我在 spring-data-jpa 中执行一个 Postgres 查询

@Transactional
public interface JournalAdd extends CrudRepository<Journal, Long> {
    @Modifying
    @Query(value = "insert into journals (messageid, oldowner) values ('dgf', 'fgd')", nativeQuery = true)
    void updateJournalOldownerMessageid(Long id);
}
执行后没有错误但在表中只添加了一行没有值

o.h.type.descriptor.sql.BasicBinder      : 将参数 [1] 绑定为 [VARCHAR] - [null]
o.h.type.descriptor.sql.BasicBinder      : 将参数 [2] 绑定为 [VARCHAR] - [null]

Postgres 表 journals

@Entity
@Table(name = "journals")
public class Journal implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "oldowner")
    private String oldowner;
    @Column(name = "messageid")
    private String messageid;
}
英文:

Please, help me execute a Postgres query in spring-data-jpa:

@Transactional
public interface JournalAdd extends CrudRepository&lt;Journal, Long&gt; {
        @Modifying
        @Query(value = &quot;insert into journals (messageid, oldowner) values (&#39;dgf&#39;, &#39;fgd&#39;)&quot;, nativeQuery = true)
        void updateJournalOldownerMessageid(Long id);
}

After execute no errors but in table added just one rows without values

o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [null]
o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [null]

Postgres table journals:

@Entity
@Table(name = &quot;journals&quot;)
public class Journal implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = &quot;oldowner&quot;)
    private String oldowner;
    @Column(name = &quot;messageid&quot;)
    private String messageid;

答案1

得分: 1

如果您使用了 nativequery=true,那么在 @Query 中必须使用纯粹的 PostgreSQL SQL。您目前在 @Query 中使用了 JPQL,但是告诉 JPA 将其作为本地查询执行。

请将您的 @Query 值更改为您在此处提供的查询。您的查询应该类似于:

@Modifying
@Query(value = "INSERT INTO journals (messageid, oldowner) select m.id, m.owner from message m where m.id = ?1", 
    nativeQuery = true)
void updateJournalOldowner(Long id);
英文:

If you are using nativequery=true, then you have to use pure postgres sql in @Query. You are using JPQL in @Query but telling JPA to execute is as a native query.

Change your @Query value with the query if have provided here. Your query should look like

@Modifying
@Query(value = &quot;INSERT INTO journals (messageid, oldowner) select m.id, m.owner from message m where m.id = ?1&quot;, 
    nativeQuery = true)
void updateJournalOldowner(Long id);

huangapple
  • 本文由 发表于 2020年10月25日 18:24:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64522647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定