【发布时间】: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