我试图在 Spring Boot 应用程序中通过 Hibernate 创建的 MySQL 数据库条目上创建一个 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> { }
所以我想要的是当我在 Controller 中初始保存实体时,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 语句是:
更新 all_contacts SET imgpath = '/savedir/contactImgId123456' WHERE contactid = 12345;
我不确定这是否可行,但如果可行,我该怎么做?
最佳答案
您可以通过两次保存来完成。
第一:
contactDao.save(contact);
第二组图片路径:
contact.setImgpath('/savedir/contactImgId'+contact.getId());
contactDao.save(contact);
关于java - 在 Spring Boot 中初始保存后更新 Hibernate 存储库条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649248/