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

xvw2m8pv  于 2024-01-09  发布在  Spring
关注(0)|答案(1)|浏览(325)
  1. @Override
  2. @Transactional
  3. public void saveBody(String body) {
  4. var entityPath = new QWord("word");
  5. var query = new JPAQuery<>(this.entityManager);
  6. JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(this.entityManager);
  7. jpaQueryFactory.insert(entityPath).set(entityPath.body, body).execute();
  8. }

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

t8e9dugd

t8e9dugd1#

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

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

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

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


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

  1. @Autowired
  2. private WordRepository wordRepository;


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

  1. Word word = new Word();
  2. word.setBody(body)
  3. wordRepository.save(word);

展开查看全部

相关问题