繁体   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