簡體   English   中英

如何使用Spring Boot JPARepository更新postgres表?

[英]How to update postgres table with Spring Boot JPARepository?

我有一個使用JPARepository將對象提交到Postgres DB的Spring Boot應用程序。 我的存儲庫的代碼如下:

public interface TestObjectDao extends JPARepository<TestObject, Long>   {

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

TestObject save(TestObject testObject);
}

當我想創建時,在我的服務實現中(在上述接口上實現),我使用了“保存”方法。 但是,當我嘗試更新時,它既不會創建條目也不會對其進行更新。

如何更新Postgres數據庫中的記錄? 以下是我用於更新的代碼段:

@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;
  }

}

我瀏覽了所有相關帖子,但沒有得到滿意的解決方案。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM