【问题标题】:Update a Hibernate Repository Entry after initial save in Spring Boot在 Spring Boot 中初始保存后更新 Hibernate 存储库条目
【发布时间】:2017-10-09 14:48:46
【问题描述】:

我试图在 Spring Boot 应用程序中通过 Hibernate 创建的 MySQL DB 条目上创建一个 UPDATE 语句,但我无法通过谷歌搜索找到如何在这条路线上执行此操作。

我有一个实体,它会在最初由其 CrudRepository 保存后自动生成主键 ID:

@Entity
@Table(name = "all_contacts")
public class Contact {


  private BigInteger userId;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column( name="contactid")
  private BigInteger contactId;

  @NotNull
  private String name;

  private String imgPath;

   // getters and setters

}

这是用作 DAO 的 CRUDRepository

public interface ContactRepository extends CrudRepository<Contact, Long> { }

所以我想要的是当我在控制器中初始保存实体时 imgPath 为空:

// within the controller
@Autowired
ContactRepository contactDAO;

public void saveContact(SomeDTO dto) {
   Contact contact = //... fields set and initialized
   contactDao.save(contact);
   BigInteger contactId = contact.getContactId();
   // do something here to save and set contact's imgPath in the DB
}

所以我想做的是,现在contactId 字段已经生成。检索contactId 并使用Hibernate 执行基本上是UPDATE 语句的操作,以便我可以将SQL 列imgPath 中的行设置为/savedir/contactImgId123456 之类的东西

所以,假设生成的contactID 是:12345,基本上我尝试执行的 SQL 语句将是: UPDATE all_contacts SET imgpath = '/savedir/contactImgId123456' WHERE contactid = 12345;

我不确定这是否可行,但如果可行,我该怎么做?

【问题讨论】:

    标签: java mysql spring hibernate spring-mvc


    【解决方案1】:

    你可以通过两次保存来做到这一点。

    第一:

    contactDao.save(contact);
    

    第二组图片路径:

    contact.setImgpath('/savedir/contactImgId'+contact.getId());
     contactDao.save(contact);
    

    【讨论】:

    • 哦,太好了!我环顾四周,并在说完成后更新它,这类似于使用 findOne() 方法,例如Contact oldContact = findOne(12345),对吗?那么在对象关闭之前事务是否真正完全提交?
    【解决方案2】:

    在 spring boot 中,你可以试试 spring data jpa 。 保存对象后,对象将处于持久状态。当您更新对象的属性时,如果会话没有关闭,jpa 或 hibernate 将自动更新数据库。所以,你可以在服务类中做你想做的事,并配置事务

    【讨论】:

    • 请包含代码 sn-p 来演示您要解决的问题。
    猜你喜欢
    • 2018-06-15
    • 2016-06-19
    • 1970-01-01
    • 2020-09-19
    • 2021-11-07
    • 2016-04-12
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多