Trouble adding image binairy to a model that has other properties as well. Photo model has title as wel ,without title I am able to save the image
//payee model
public class Payee {
#Id
private String id;
private String name;
private Photo photo;
//photo model
public class Photo {
#Id
private String id;
private String title;
private Binary image;
//Constuctor
//Getter and Setter
//add photo
#PostMapping('/photos/add')
public String addPhoto(#RequestBody Payee payee , #RequestParam("title") String title, #RequestParam("image") MultipartFile image, Model model)
throws IOException {
String id = photoService.addPhoto(title,image);
return id;
}][1]][1]
figured it out,
set image as binary in model
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Payee> update(#RequestPart("payee") #Valid Payee payee, #RequestPart("file") #Valid MultipartFile image) throws IOException
{
// routine to update a payee including image
if (image != null)
payee.setImage(new Binary(BsonBinarySubType.BINARY, image.getBytes()));
Payee result = payeeRepository.save(payee);
return ResponseEntity.ok().body(result);
}
Related
When submiting data to my service, I'm getting the following error:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'entity' is not present] error and dont know what im missing any suggestion would help
Dont know what is the problem using similar api
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api/entity")
public class EntityController {
#Autowired
IEntityRepository entityRepository;
#RequestMapping(value = "/updateEntity", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Entity> updateEntity(#RequestPart("entity") #Valid Entity entity, #RequestPart("file") #Valid Optional<MultipartFile> image) throws IOException {
// routine to update a entity including image
byte[] imageData = null;
if (image.isPresent() && image.get() != null)
imageData = image.get().getBytes();
if (imageData == null && entity.getId() != null) {
Optional<Entity> readEntity = entityRepository.findById(entity.getId());
if (readEntity.get() != null)
imageData = readEntity.get().getImage().getData();
}
if (imageData != null) {
entity.setImage(new Binary(BsonBinarySubType.BINARY, imageData));
}
Entity result = entityRepository.save(entity);
return ResponseEntity.ok().body(result);
}
Models (did not add constructor or getters and setters)
public class Entity {
#Id
private String id;
private Types types;
private String username;
private String name;
private String surname;
private Binary image;
private String address;
private String email;
private String contactNo;
private String country;
private Status status;
private List<UserRolls> userRolls;
private MemberShip memberShip;
private Staff staff;
private Payee payee;
private List<BankAccount> userBankAccount;
private String loginCode;
#NotBlank
#Size(max = 120)
private String password;
React snippet using values from formik and getting the binairy data from the image im selecting ,dont suspect it to be the image
async function submitForm(values) {
/* routine to send the request to the server/*
const formData = new FormData();
var postData = values;
formData.append(
'bank',
new Blob([JSON.stringify(postData)], {
type: 'application/json',
})
);
if (imageData) {
formData.append('file', imageData);
}
//Send Api request
return Api(`auth/updateUser`, 'Post', formData);
}
Problem was in the frontend had an spelling error where I submit and append bank should have changed to entity
Having trouble creating only one model ,created a photo model and payee model but want to add photo model to payee model but wont accept the binary part of photo . Keep getting binary error when trying to post off of postman ,aware that need to change controller but a bit stuck ,any links or advise for a begginner would be gratefull
//Payee model
public class Payee {
#Id
private String id;
private Contact contact;
private String notes;
private String project;
private String member;
private Integer staffMember;
private Photo photo;
private BankAccount userBankAccount;
private PayeeBankAccount payeeBankAccountList;
//Payee constructor
public Payee(Contact contact, String notes, String project, String member, Integer staffMember,
Photo photo, BankAccount userBankAccount, PayeeBankAccount payeeBankAccountList) {
this.contact = contact;
this.notes = notes;
this.project = project;
this.member = member;
this.staffMember = staffMember;
this.photo = photo;
this.userBankAccount = userBankAccount;
this.payeeBankAccountList = payeeBankAccountList;
}
// Getters and Setters
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public Contact getContact() { return contact; }
public void setContact(Contact contact) { this.contact = contact; }
public String getNotes() { return notes; }
public void setNotes(String notes) { this.notes = notes; }
public String getProject() { return project; }
public void setProject(String project) { this.project = project; }
public String getMember() { return member; }
public void setMember(String member) { this.member = member; }
public Integer getStaffMember() { return staffMember; }
public void setStaffMember(Integer staffMember) { this.staffMember = staffMember; }
public Photo getPhoto() {return photo;}
public void setPhoto(Photo photo) {this.photo = photo;}
public BankAccount getUserBankAccount() { return userBankAccount; }
public void setUserBankAccount(BankAccount userBankAccount) { this.userBankAccount = userBankAccount}
public PayeeBankAccount getPayeeBankAccountList() { return payeeBankAccountList; }
public void setPayeeBankAccountList(PayeeBankAccount payeeBankAccountList){this.payeeBankAccountList= payeeBankAccountList; }
}
//photo model
public class Photo {
#Id
private String id;
private String title;
private Binary image;
//Photo constructor
public Photo(String id, String title, Binary image) {
this.id = id;
this.title = title;
this.image = image;
}
public Photo(String title) {
super();
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
#Override
public String toString() {
return "Photo \[id=" + id + ", title=" + title + ", image=" + image + "\]";
}
}
//photo service
#Service
public class PhotoService {
#Autowired
private PhotoRepository photoRepo;
public Photo getPhoto(String id) {
return photoRepo.findById(id).get();
}
public String addPhoto(String title, MultipartFile file) throws IOException {
Photo photo = new Photo(title);
photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes()));
photo = photoRepo.insert(photo);
return photo.getId();
}
}
Photo and payee PostMapping should be in one ,dont know where to go with this part
//add payee
#PostMapping('/addPayee')
public void insert(#RequestBody Payee payee){
this.payeeRepository.save(payee);
}
//add photo
#PostMapping('/photos/add')
public String addPhoto(#RequestBody Payee payee , #RequestParam("title") String title, #RequestParam("image") MultipartFile image, Model model)
throws IOException {
String id = photoService.addPhoto(title,image);
return id;
}][1]][1]
[1]: https://i.stack.imgur.com/lF6KZ.png
Figured it out in you model have image as binary and in youre controller have some like
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity update(#RequestPart("payee") #Valid Payee payee, #RequestPart("file") #Valid MultipartFile image) throws IOException
{
// routine to update a payee including image
if (image != null)
payee.setImage(new Binary(BsonBinarySubType.BINARY, image.getBytes()));
Payee result = payeeRepository.save(payee);
return ResponseEntity.ok().body(result);
}
I have a User POJO having fields:
#Id
private String _id;
private String phone;
private String email;
private String password;
private String userName;
private String dob;
private String gender;
private String city;
private String pincode;
private String status;
private String validUpto;
private List<String> userRole;
private String persona;
I saved all the fields in MongoDB (document).
Now I want to update only few fields like city, Pincode.
I also refer this question, but it is not giving the answer via MongoRepository.
is there any way we can update only few fields via MongoRepository instead of MongoTemplate.
The repository doesn't provide an 'update' operation only .save(object);
But you can update it by retrieving the Object from the repository, change the relevant fields. Afterwards, you save the updated object to the repository.
Which will get you the desired result of 'updating'.
Spring-boot/SpringRepository example.
#Autowired
UserRepository userRepository;
#Test
public void testUpdateUser() throws Exception {
User foundUser = userRepository.findById("1");
foundUser.setCity("Helsinki");
// foundUser.setOtherFields("new values");
userRepository.save(foundUser); // Will 'update' but it essentially replaces the entity in database
}
I'm having a problem understanding/figuring out a problem I'm having with OpenJPA and was hoping someone here can help out.
Basically, I have the following two entities:
#Entity
#Table(name = "images")
public class Image {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "path")
private String path;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
#Entity
#Table(name = "people")
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "image_id")
#ForeignKey(name = "fk_person-image")
private Image image;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
}
As you can see, a Person can have an Image. This is an optional column and supports a null value. When a call from the REST Web Service comes in to update a Person changing the Image field, if the Image is being set to null the database isn't being updated, however if the Image is being changed to a different existing Image, it is saving.
I suspect this has something to do with the fact that the Person is coming in from the outside (detached), since if I obtain the Person from the DAO Service, set the Image to null and call the update/merge method using that instance it is updating the DB.
I was able to get it to work by adding the following property:
<property name="openjpa.DetachState" value="fetch-groups(DetachedStateField=false)"/>
However this seems to have some drawbacks as other relationships aren't being populated anymore when fetching from the DB. (Rooms in a Building when retrieving the Building for example)
Has anyone encountered this before? Any ideas on how this should be handled? I'm tempted to test out Hibernate/Eclipselink to see if/how they handle this.
Any help would be appreciated, I've been racking my brain around this for the past 2 days.
I have one User class like this:
#Document(collection = "users")
public class User {
#Id
private String id;
String username;
String password;
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "User[id=" + id + ", username=" + username + ", password=" + password + ", description"
+ description + "]";
}
}
I am able to perform limited update. Like:
Query searchQuery = new Query(Criteria.where("id").is("shashi"));
mongoDBClient.updateFirst(searchQuery, Update.update("password", "newpassword"), User.class);
Now if I want to update rest other fields(username and description) of User class, I need to call updateFirst method so many times.
I want to avoid this and pass the entire object to updateFirst method. Something like:
mongoDBClient.updateFirst(searchQuery, Update.update(userObject), User.class);
Basically, I want to edit all/multiple fields in one call using java POJO object. How I can achieve this?
Edit/All multiple fields in one call using java POJO object, can be done as shown below
1) Query the document which need to be updated --> we get the java object
2) Do all modifications in the java object
3) Save the object
Code:
Query query = new Query();
query.addCriteria(Criteria.where("id").is("shashi"));
User user = mongoOperation.findOne(query, User.class);
//modify the user object with the properties need to be updated
//Modify password and other fields
user.setPassword("newpassword");
user.setDescription("new description");
user.setUsername("NewUserName");
//save the modified object
mongoOperation.save(user);