advanced queries spring boot - java

Can anyone explain me how to add advanced queries in crudrepository for example in my case I want to search users by their firstname.
Below is my AppUsers Class
public class AppUsers {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int id;
#Column(name = "firstname")
public String firstName;
#Column(name = "lastname")
public String lastName;
public AppUsers() {
}
public AppUsers(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
This is the AppUsers Repository :
package com.developer.SpringMySQL.models;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface AppUsersRepo extends PagingAndSortingRepository<AppUsers,Integer> {
}
and this is the controller :
#Controller
public class MainController {
private AppUsersRepo usersRepository;
#Autowired
AppUsersRepo appRepo;
#RequestMapping("/")
public ModelAndView doHome() {
ModelAndView mv = new ModelAndView("index");
mv.addObject("lists", appRepo.findAll());
return mv;
}
}

It's naming convention on the repository method.
In your case you need to create a method in the Repository interface :
Set findByFirstName(String pFirstName);
See following links for more infos on the naming convention :
https://spring.io/guides/gs/accessing-data-mysql/
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

in Spring JPA you can do it like this:
Set<AppUsers> findByFirstName(String firstName);
Or in more complex you can use mysql like this (example from project of mine):
#Query("SELECT NEW ps.exalt.timeoff.server.response.BasicInformation(e.id,e.name,e.email,e.profilePicture) FROM Employee e join e.roles r where r.id = 5 AND e.id > 0 AND activated= :enable")
Page<BasicInformation> findAllEmpWithApprovers(Pageable pageRequest,#Param("enable")boolean enable);
for more info check docs: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation

Related

Springboot Hibernate read data from existing table on SQL Server

I have an existing Table in SQL Server.
CREATE TABLE [dbo].[STUDENTS](
[ID] [int] NOT NULL,
[FIRSTNAME] [varchar](50) NOT NULL,
[LASTNAME] [varchar](50) NOT NULL,
[EMAIL] [varchar](100) NOT NULL,
[AGE] [int] NOT NULL,
[ADDRESS] [varchar](3000) NOT NULL,
PRIMARY KEY (ID)
);
I have created this entity in JAVA to me able to extract data using Hibernate.
package com.My_task_be.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTS")
public class Student {
#Id
#Column(name = "ID")
public int id;
#Column(name = "FISRTNAME")
public String firstName;
#Column(name = "LASTNAME")
public String lastName;
#Column(name = "EMAIL")
public String email;
#Column(name = "AGE")
public int Age;
#Column(name = "ADDRESS")
public String Address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
This is the repository
#Repository
public interface StudentRepository extends CrudRepository<Student, Integer>{
List<Student> findAll();
}
This is the controller
#RestController
public class AppController {
#Autowired
private StudentRepository studentRpository;
#GetMapping("/getAllStudents")
public List<Student> getAllStudents(){
return studentRpository.findAll();
}
#GetMapping("/helloWorld")
public String helloWorld(){
return "Hello World!";
}
}
When i run http://localhost:8080/getAllStudents
I get Invalid column name 'fisrtname'.
I dont want hibernate to create a new table I just want it to read from an existing table.
And I have specified the Column names but still it did not work.
Any ideas?
You have a typo in FISRTNAME. It is FIRSTNAME, change as below
#Column(name = "FIRSTNAME")
public String firstName;

How can I get a value from a map with a key?

I am trying to find a specific object. I'm using the following code, but it seem like get only sends back a Boolean that verifies that there is a key with this name, but not an array of Boolean values that I need to use in my program:
private Map<User, ArrayList<Boolean>> userDayOfVacationMap;
public ArrayList<Boolean> getUserVacationList(User key){
return this.userDayOfVacationMap.get(key);
}
Is there a method for this?
Here is the User object:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
#OneToMany(mappedBy="user", cascade = CascadeType.ALL)
public Set<Vacation> vacations;
public User(String firstName, String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
public User(){}
public Set<Vacation> getVacations() {
return vacations;
}
public void setId(int id){
this.id = id;
}
public Integer getId(){
return this.id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
However, I can't add a variable in this function, because it would add non-useful information into my database.

Spring data elasticsearch sorting

I am trying to learn spring data elasticsearch, and created a sample project. Right now, I am trying to get familiar with the mechanics of sorting.
Simply put, I have a Person class, that has a firstName and lastName field. I am trying to sort on the lastNameField.
Here is my Person class:
#Document(indexName = "entities", type = "person", shards=1, replicas=0)
public class Person {
#Id
private String id;
#Field(type=FieldType.String, index=FieldIndex.not_analyzed)
private String firstName;
#Field(type=FieldType.String, index=FieldIndex.not_analyzed)
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is my DAO logic:
#Override
public Page<Person> getPeople(int pageNumber, int pageSize, Direction direction, String...sortFields) {
return personRepository.findAll(new PageRequest(pageNumber, pageSize, direction, sortFields));
}
The personRepository is an empty interface that extends PagingAndSortingRepository
And the actual call:
int pageSize = 1;
int currentPageNumber = -1;
boolean morePages = true;
while(morePages){
Page<Person> results = personDataHandler.getPeople(currentPageNumber+1, pageSize, Direction.DESC, "firstName");
List<Person> people = results.getContent();
if(!CollectionUtils.isEmpty(people)){
for(Person currentPerson: people){
System.out.println("[firstName: "+currentPerson.getFirstName()+", lastName: "+currentPerson.getLastName()+"]");
}
}
currentPageNumber++;
morePages = results.hasNext();
}
Could having a page size of 1 be the issue?

JPA ManytoMany Relationship "JoinColumn cannot be resolved to a type" error

I am using Spring boot and trying to implement many to many relationship between User and Skill. I have a table users_skills with columns user_id and skill_id. I keep getting "JoinColumn cannot be resolved to a type" error in #JoinColumn annotations in STS when trying to implement the relationship. Below is my User class
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String email;
private String firstName;
private String lastName;
private List<Skill> skills = new ArrayList<Skill>();
protected User() {}
public User(String email,String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id ;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email ;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName ;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName ;
}
#ManyToMany
#JoinTable(name="users_skills",
joinColumns={#JoinColumn(name="user_id")},
inverseJoinColumns={#JoinColumn(name="skill_id")})
public List<Skill> getSkills(){
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills ;
}
}
Just write this at the head of your class
import javax.persistence.JoinColumn;
Sometime eclipse doesn't show the link to import it in context menu, but it's there. Hope it will help someone.

How to Retrieve the subfields stored in MongoDB

The below data is stored in MongoDB. I am using Spring-Data and storing the data into mongoDB.
If I want to retrieve the fields ("id" or "Name") I can able to do, but if I want to retrieve the sub fields ("firstName" or "lastName")I can't.
(eg.)If I want to retrieve sub field "lastName" from the below data I can't.Can anyone help me in this regards.
Thanks in advance.
Data Stored in MongoDB:
{
"id":101,
"name": {"firstName":"Mark",
"lastName":"Antony"
}
}
The Code I am using is:
PersonService.java
public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME);
}
PersonController.java
#RequestMapping(value = "/person/search", method = RequestMethod.GET)
public String search(#ModelAttribute Audit audit, ModelMap model) {
model.addAttribute("personList", personService.searchPerson(audit));
return "output";
}
Audit.java
#Document
public class Audit {
#Id
private String id;
private List<NameDetails> name;
public String getId() {
System.out.println("Person: getId");
return id;
}
public void setId(String id) {
System.out.println("Person: setId");
this.id = id;
}
public List<NameDetails> getName() {
System.out.println("Audit: getName");
return name;
}
public void setName(List<NameDetails> name) {
System.out.println("Audit: setName");
this.name = name;
}
}
NameDetails.java
package com.register.mongo.model;
public class NameDetails {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}
}
(output.jsp)UI Page
<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td>
</tr>
<tr>
<td>${person.lastName}</td>
</tr>
</c:forEach>
</table>
If i understand well, you should make an extra class and use it in the Audit class
public class NameDetails{
private String FirstName;
private String LastName;
public String getFirstName() {
return id;
}
public void seFirstName(String fisrtName) {
this.FirstName= fisrtName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
and use this class in the Audit.class
#Document
public class Audit {
#Id
private String id;
private List name<NameDetails>;
and then the setters and getters

Categories

Resources