I'm stuck trying to save #DBRef inside document - java

I have document user and document adventureHolidays. There is a lot of users and as well adventure holidays. So far I created a controller that return me a random element from adventureHolidays document. On that page I have button to randomize again and on each click new document from adventureHoliday is provided. What is my goal right now? I want to create a button that will actually save a current document that is provided as field in user document, so he can see on his profile which adventureHolidays he has saved.
This is user entity
#Document
public class User {
#Id
private String id;
#Indexed(unique = true)
#NonNull
private String username;
#Indexed(unique = true)
#NonNull
private String email;
#JsonIgnore
#NonNull
private String password;
#DBRef
private List<AdventureHolidays> adventureHolidaysList;
And this is AdventureHoldiays
#Document("adventureholidays")
public class AdventureHolidays {
#Id
private String id;
private String title;
private String description;
private String state;
private String typeOfAdventureHolidays;
private String image;
How I can now save document that is random returned to user to user entity? I even dont know where to start. Guess I need ID and that to save somehow it to field in user document

Related

Saving a element from one document to user document

I have those two entites:
#Document
public class User {
#Id
private String id;
#Indexed(unique = true)
#NonNull
private String username;
#Indexed(unique = true)
#NonNull
private String email;
#JsonIgnore
#NonNull
private String password;
#Document("adventureholidays")
public class AdventureHolidays {
#Id
private String id;
private String title;
private String description;
private String state;
private String typeOfAdventureHolidays;
private String image;
I want to create a service that will save into user document element from adventureholidays.
I have a service to return a random element from adventureholidays document, so If user want to save that document I would like to save title of that document into user document.
So somehow I need to take a ID of current adventureholiday that is provided and then to save to current logged user.
I am just giving you the logic, add
#DBRef
private AdventureHolidays adventureHolidays;
in your User class it will map both classes, then get the id of holiday from the save button using link or value from your form and then using that id in find() function and fetch the data of that particular holiday store it in a object ie. holiday.
Now just save it in service class inside a method like this:
User user=new User();
user.setAdventureHolidays(holiday);
// create a userRepository which extends MongoRepository
userRepository.save(user);

How to update only chosen records from form?

The main question is, how to update just a few chosen fields from our form. I would like to give user choice which fields they want to update. For example, I have the form class:
public class UserRegistrationform {
private Integer userId;
#NotNull
private String name;
#NotNull
private String surname;
#Email
#NotNull
private String email;
#NotNull
private Integer genderId;
#NotNull
private Integer groupId;
#NotNull
private List<ContactInfoDto> contactsInfo;
#NotNull
private String userSecretkey;
#NotNull
private String password;
#NotNull
private boolean enabled;
#NotNull
private boolean resetPassword;
After that I'm setting fields in #Entity class User, and for example, if user want to change just their name and surname, I want to take the rest of the fields from the existing User, by findById() method and after that change a few fields and save the changed object to the database.
#BeshambherChaukhwan ok, maybe will be easier where I will use example, so I have a controller when is method:
#PostMapping(value = "{id}/updateuser")
public ResponseDTO updateUser(#PathVariable int id, #RequestBody UserRegistrationform userForm, BindingResult bindingResult) {
User user = userRepository.findById(id);
if (user == null) {
return ResponseDTO.of(Messages.Error_UserNotFound_MSG.getMessage(), ErrorCodes.NOT_FOUND);
} else if (bindingResult.hasErrors()) {
return ResponseDTO.of(bindingResult.getAllErrors().toString(), ErrorCodes.INVALID_FIELDS);
}
user.setName(userForm.getName);
user.setSurname(userForm.getSurname);
user.setEmail(userForm.getEmail);
.
.
.
userRepository.save(user);
return ResponseDTO.of(Messages.SUCCESS_Update_MSG.getMessage());
}
The problem is, like you noticed when in form someone miss few fields, and I will update right fields by null values

How can we save the form data from jsp file in database using spring boot?

I am creating a spring boot API which basically asks the user to create an account.
The account details are showed on a form.
I want to fetch the details from the form and save that to the database(MYSQL).
The model class is as follows:
#Table(name = "user")
public class User {
#Id
#Column(name = "ID")
private int ID;
#Column(name = "Fname")
private String fName;
#Column(name = "Lname")
private String lName;
#Column(name = "dob")
private String dob;
#Column(name = "email")
private String email;
#Column(name = "pWord")
private String pWord;
}
The controller class is as follows:
public class MController {
#Autowired
private UserRepository userRepository;
#PostMapping("/successSignUp")
public String dataToDB(#ModelAttribute("User") User formData, Model model) {
userRepository.save(new User(formData.getFname(), formData.getLname(), formData.getDob(), formData.getEmail(), formData.getPassword()));
model.addAttribute("user", new User());
return "welcomeUser";
}
When i am executing this code, i am getting the following error:
java.sql.SQLSyntaxErrorException: Unknown column 'p_word' in 'field list'
What am I doing wrong here?
Thanks in advance.
Spring framework changes the camel case to snake case internally.
This is part of Spring Boot Naming Strategies:
We can override these values, but by default, these will:
Change camel case to snake case
Replace dots with underscores
Lower-case table names
Can you try to update column name as pword instead of pWord ?
#Column(name = "pword")
private String pWord;
it will be considered as p_word if you use 'pWord'. please update column name as 'pword' and try.
example:
#Entity
public class Account {
#Id
private Long id;
private String defaultEmail;
}
And then turn on some SQL debugging in our properties file:
hibernate.show_sql: true
At startup, we'll see the following create statement in our logs:
Hibernate: create table account (id bigint not null, default_email varchar(255))
The easiest solution to fix this is to put the column names in lowercase or uppercase.
#Column(name = "pword")
private String pWord;
or
#Column(name = "PWORD")
private String pWord;
This will avoid that spring convert the name into snakecase.
Name of the columns in MySql are not case sensitive, so it will work.

returning specific version of DTO based on user role

I have a JobDTO class
class JobDTO{
private Integer id;
private String jobTitle;
private String secreateData;
...
}
I have a BidDTO class
class BidDTO{
private Integer id;
private String bidDetails;
private JobDTO jobDTO;
public BidDTO(Integer id, String bidDetails, JobDTO jobDTO){
this.id = id;
this.bidDetails = bidDetails;
this.jobDTO = jobDTO;
}
}
The reason I have JobDTO in BidDTO is because when I return a bid I need to return the related job details as well. The question is that what I want to hide the secretData in JobDTO from user based on users's role?
One solution could be to put individual JobDTO fields in BidDTO that I want to show to user rather than having a JobDTO object as part of it but what if there are 100 fields in JobDTO and I only have one secretData field that want to hide.

How to link datastore with document using key

I will be very thankful if someone could help me to solve this problem
as I have already spent a lot of time on it.
The frontend of my application sends employee data to server end,
which creates Emmployee object and saves the data on datastore. My
application provides the keyword search functionality on title,
company and jobDesc so I am using Search Api.
The problem is that I want to use datastore for storing the complete
data and document for storing searchable data. How can I link
datastore with document? I know it can be achieved if I set employee’s
key as document id but the problem is how will I get the key of the
data which is being store. If I try to get key using e.getKey() that
obviously returns nullPointerException because it does have the key at
that time.
I can achieve this by reading all employee data stored on datastore
and creating document with it and setting employee’s key as document
id but I want to create document as the data is received from frontend
of application.
//EmployeeServlet
PersistenceManager pm = PMF.get().getPersistenceManager();
Employee e = new Employee(title, company, location, category,
jobType, gender,
careerLevel, salaryRange,
sector, jobDesc);
Document newDoc = Document.newBuilder().setId(???)
.addField(Field.newBuilder().setName("title").setText(title))
.addField(Field.newBuilder().setName("company").setText(company))
.addField(Field.newBuilder().setName("jobDesc").setText(jobDesc)).build();
SearchIndexManager.INSTANCE.indexDocument("Employee", newDoc);
pm.makePersistent(e);
//Employee
#PersistenceCapable
public class Employee {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private String title;
#Persistent
private String company;
#Persistent
private String location;
#Persistent
private String category;
#Persistent
private String jobType;
#Persistent
private String gender;
#Persistent
private String careerLevel;
#Persistent
private String salaryRange;
#Persistent
private String sector;
#Persistent
private Text jobDescription;
public Employee(String title, String company, String location,
String category,
String jobType, String gender,
String careerLevel, String salaryRange,
String sector,
String jobDescription) {
super();
this.title = title;
this.company = company;
this.location = location;
this.category = category;
this.jobType = jobType;
this.gender = gender;
this.careerLevel = careerLevel;
this.salaryRange = salaryRange;
this.sector = sector;
this.jobDescription = new Text(jobDescription);
}
}
Save employee entity. Get the id.
Set this id as a document id, index the document.
Both steps can be done in the same server call. Just move your makePersistent() before you create a document.

Categories