【问题标题】:How to update postgres table with Spring Boot JPARepository?如何使用 Spring Boot JPARepository 更新 postgres 表?
【发布时间】:2016-10-25 16:40:04
【问题描述】:

我有一个使用 JPARepository 将对象提交到 Postgres DB 的 Spring 启动应用程序。我的存储库的代码如下:

public interface TestObjectDao extends JPARepository<TestObject, Long>   {

List<TestObject> findByTestRefIdAndTestType(String testRefId,
        Short testType);

TestObject save(TestObject testObject);
}

当我想创建时,在我的服务实现(实现上述接口)中,我使用了“保存”方法。但是,当我尝试更新时,它既不会创建条目也不会更新它。

如何更新 Postgres 数据库中的记录?下面是我的代码 sn-p 用于更新:

@Component
public class TestObjectServiceImpl implements TestObjectService {

  @Inject
  private TestObjectDao TestObjectDao;

  @Override
  public TestObjectResponse createTestObject(String testRefId, String testType, TestObject testObject) throws Exception{

    --
    --
    --

    try {
            //update object
            testObject = TestObjectDao.save(testObject);
        }
    }
    catch (Exception ex) {
        throw new Exception("Object could not be modified");
    }

    TestObjectResponse testObjectResponse = new TestObjectResponse();
    testObjectResponse.setVal(testObject);

    return testObjectResponse;
  }

}

我浏览了所有相关帖子,但没有得到满意的解决方案。

【问题讨论】:

    标签: java postgresql spring-boot


    【解决方案1】:

    Spring 通过检查实体的 ID 来检测它是否需要保存或创建实体。

    在您的情况下,您需要先选择它,以便 Spring 正确填充实体:

    try {
            testObject = TestObjectDao.findOne(testRefId);
            //update object
            testObject = TestObjectDao.save(testObject);
    }
    

    请参考第2.2.1节:
    http://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html

    请注意,如果只更新某些列,则使用起来效率更高:

    @Modifying
    @Query("update User u set u.firstname = ?1 where u.lastname = ?2")
    int setFixedFirstnameFor(String firstname, String lastname);
    

    【讨论】:

    • 很高兴听到。那么请将其标记为正确答案。
    猜你喜欢
    • 2018-01-13
    • 2020-11-10
    • 2019-03-07
    • 2020-03-09
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多