Spring Data Jpa 如何使用查询语句将参数值插入到数据库中?

xvw2m8pv  于 4个月前  发布在  Spring
关注(0)|答案(1)|浏览(78)
@Override
    @Transactional
    public void saveBody(String body) {
       var entityPath = new QWord("word");
       var query = new JPAQuery<>(this.entityManager);
       JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(this.entityManager);
       jpaQueryFactory.insert(entityPath).set(entityPath.body, body).execute();    
    }

字符串
代码有什么错?
错误:由以下原因引起:org.hibernate.query.SemanticException:发生查询异常[插入到Word(body)word.body =?1]
我得到了这个
错误:由以下原因引起:org.hibernate.query.SemanticException:发生查询异常[插入到Word(body)word.body =?1]

t8e9dugd

t8e9dugd1#

它看起来不是创建实体的正确方式。
正确的方法应该是这样的:

SQLInsertClause insertClause = new SQLInsertClause(connection, SQLTemplates.DEFAULT, entityPath)
    .set(entityPath.body, body)
    .execute();

字符串
引用:DslQuery插入
我认为使用JPA repository本身创建实体更容易。
用于管理Word实体的JPA存储库。

// assuming the ID of the entity Word is Long
public interface WordRepository extends JpaRepository<Word, Long> {
}


在服务层中,自动连接存储库。

@Autowired
private WordRepository wordRepository;


然后,您可以使用它来保存您的新实体或更新它们。

Word word = new Word();
word.setBody(body)

wordRepository.save(word);

相关问题