Reputation: 3594
I am trying to essentially create an UPDATE
statement on an entry to my MySQL DB created through Hibernate in a Spring Boot app, and I haven't been able to find how to do this in this route through google searches.
I have an Entity which generates a primary key ID automatically once it is initially saved by its CrudRepository:
@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
}
Here is its CRUDRepository
used as the DAO:
public interface ContactRepository extends CrudRepository<Contact, Long> { }
So what I want is the imgPath is left empty when I do the initial saving of the Entity in the controller:
// 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
}
So what I want to do, is now that the contactId
field has been generated. Is retrieve the contactId
and use Hibernate to perform what would essentially be an UPDATE
statement so that I can set that row in the SQL column imgPath
to something like /savedir/contactImgId123456
So, say the contactID
generated was: 12345, basically the SQL statement I'm trying to then execute would be:
UPDATE all_contacts SET imgpath = '/savedir/contactImgId123456' WHERE contactid = 12345;
I'm not sure if this is feasible, but if it is, how would I do that?
Upvotes: 0
Views: 951
Reputation: 3
In spring boot ,you can try spring data jpa . After you save the object, the object will be persisting state. When you update the attribute of the object ,if the session is not closed,jpa or hibernate will update database automatically. So,you can do what you want in service class,and config transaction
Upvotes: 0
Reputation: 614
You can do it with twice save.
First :
contactDao.save(contact);
Second set image path:
contact.setImgpath('/savedir/contactImgId'+contact.getId());
contactDao.save(contact);
Upvotes: 1