繁体   English   中英

在Spring Boot中进行初始保存后更新Hibernate Repository条目

[英]Update a Hibernate Repository Entry after initial save in Spring Boot

我试图从本质上在Spring Boot应用程序中通过Hibernate创建的MySQL数据库条目上创建UPDATE语句,但我无法通过Google搜索找到如何在此路由中执行此操作。

我有一个实体,一旦它由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

}

这是它的CRUDRepository用作DAO:

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;

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

您可以保存两次。

首先:

contactDao.save(contact);

第二套图片路径:

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

在spring boot中,您可以尝试spring data jpa。 保存对象后,对象将处于持久状态。 当更新对象的属性时,如果未关闭会话,则jpa或hibernate将自动更新数据库。 因此,您可以在服务类和配置事务中完成所需的操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM