My application fails to start because spring can't see bean.
I'm trying to run mu application and add created user to db. I have no idea how to create missing bean. I found that there must be annotation #Repository above interface, so I placed it, but it still doesn't work.
User:
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
#Entity
public class User implements Serializable, UserInterface {
private static final long serialVersionUID = 8062231146287834334L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String login;
#Column
private String password;
#Column
private String email;
#Column
private Long phoneNumber;
#Column
private String firstName;
#Column
private String lastName;
#Column
private LocalDate dateOfBirth;
#Column
private String address;
#Column
private String city;
#Column
private String zipCode;
public User() {
//constructor for hibernate
}
private User(String login, String password, String email, Long phoneNumber, String firstName,
String lastName, LocalDate dateOfBirth, String address, String city, String zipCode) {
this.login = login;
this.password = password;
this.email = email;
this.phoneNumber = phoneNumber;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public String getLogin() {
return login;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getEmail() {
return email;
}
#Override
public Long getPhoneNumber() {
return phoneNumber;
}
#Override
public String getFirstName() {
return firstName;
}
#Override
public String getLastName() {
return lastName;
}
#Override
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
#Override
public String getAddress() {
return address;
}
#Override
public String getCity() {
return city;
}
#Override
public String getZipCode() {
return zipCode;
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phoneNumber=" + phoneNumber +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dateOfBirth=" + dateOfBirth +
", address='" + address + '\'' +
", city='" + city + '\'' +
", zipCode='" + zipCode + '\'' +
'}';
}
public static class UserBuilder {
private String login;
private String password;
private String email;
private Long phoneNumber;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String address;
private String city;
private String zipCode;
public UserBuilder setUserLogin(String login) {
this.login = login;
return this;
}
public UserBuilder setUserPassword(String password) {
this.password = password;
return this;
}
public UserBuilder setUserEmail(String email) {
this.email = email;
return this;
}
public UserBuilder setUserPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public UserBuilder setUserFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder setUserLastName(String lastName) {
this.lastName = lastName;
return this;
}
public UserBuilder setUserDateOfBirth(String dateOfBirth) {
this.dateOfBirth = LocalDate.parse(dateOfBirth);
return this;
}
public UserBuilder setUserAddress(String address) {
this.address = address;
return this;
}
public UserBuilder setUserCity(String city) {
this.city = city;
return this;
}
public UserBuilder setUserZipCode(String zipCode) {
this.zipCode = zipCode;
return this;
}
public User build() {
boolean isAllFielsdAreFull = login != null && password != null && email != null
&& phoneNumber != null && firstName != null
&& lastName != null && dateOfBirth != null && address != null
&& city != null && zipCode != null;
if (isAllFielsdAreFull) {
return new User(login, password, email, phoneNumber, firstName, lastName, dateOfBirth, address, city, zipCode);
} else {
throw new RuntimeException("Some fields are null!");
}
}
}
}
UserRepo:
package wawer.kamil.library;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import wawer.kamil.library.domain.User;
#Repository
public interface UserRepo extends JpaRepository<User, Long> {
}
Controller:
package wawer.kamil.library;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Controller;
import wawer.kamil.library.domain.User;
#Controller
public class Start {
private UserRepo userRepo;
#Autowired
public Start(UserRepo userRepo) {
this.userRepo = userRepo;
}
#EventListener(ApplicationReadyEvent.class)
public void run() {
User user = new User.UserBuilder()
.setUserLogin("Mareczek")
.setUserPassword("Mareczek3#")
.setUserEmail("mareczek#gmail.com")
.setUserPhoneNumber(515791468L)
.setUserFirstName("Marek")
.setUserLastName("Kowalski")
.setUserDateOfBirth("1990-12-12")
.setUserAddress("Kowalska 12")
.setUserCity("Lublin")
.setUserZipCode("20-123")
.build();
userRepo.save(user);
}
}
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://0.0.0.0:32768/library
?serverTimezone=Europe/Warsaw
spring.datasource.username=root
spring.datasource.password=root
Main class:
package wawer.kamil.library;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}
Error Logs:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-10 11:19:30.771 ERROR 6282 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in wawer.kamil.library.Start required a bean of type 'wawer.kamil.library.UserRepo' that could not be found.
Action:
Consider defining a bean of type 'wawer.kamil.library.UserRepo' in your configuration.
Process finished with exit code 1
I would like to run my application, and add user to db.
You need to enable repositories
#SpringBootApplication
#EnableJpaRepositories // this will fix the issue
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
Related
Dear Stackoverflow community,
I am new to working with generics and have problems with using genericts correctly. What I want to do is, that a static method can take a generic Object as a parameter. My idea is, to pass Entity Objects as parameter and after return a UserDetailsImpl object. So I want to make this method able to handle different entity classes and dont write boilerplatecode. For this I write an easy Box class for it.
Box.java
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Now I try to use it to pass generic object as parameter in my UserDetailsImpl.java class in the static build method:
package com.yildiz.tradilianz.security.services;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String email;
#JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(Long id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(Box<Object> user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
Now the problem is, that the passed Object doesn't know the whole get() methods I try to access like user.getId(), user.getRoles(), user.getPassword() etc. I want that the generic Box Class contains any Object but how to declare this method I need to access from it?
Otherwise it ends up with "The method getRoles() is undefined for the type Box"
What I wanted to pass as generic Object is my customer entity class, but if it returns null instead i want to test if retailer entity class works and so on in **UserDetailsServiceImpl **:
package com.yildiz.tradilianz.security.services;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yildiz.tradilianz.auth.User;
import com.yildiz.tradilianz.auth.UserRepository;
import com.yildiz.tradilianz.customer.Customer;
import com.yildiz.tradilianz.customer.CustomerDTO;
import com.yildiz.tradilianz.customer.CustomerRepository;
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
CustomerRepository customerRepository;
#Autowired
CustomerDTO customerDTO;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Check for username or email passed through username parameter
boolean valid = EmailValidator.getInstance().isValid(username);
if (valid == false) {
/*
* Build with UserDetailsImpl but if user for Customer class is null I want to try another repository and do
* something like this:
* Retailer user = retailerRepository.findByUsername(username); And if it is not null
* it should pass user Object which class is Retailer and so on.
*
*/
Customer user = customerRepository.findByUsername(username);
return UserDetailsImpl.build(user);
} else {
Customer user = customerRepository.findByEmail(username):
return UserDetailsImpl.build(user);
}
}
}
customer entity class
package com.yildiz.tradilianz.customer;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import com.yildiz.tradilianz.auth.ERole;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Size(max = 20)
private String username;
#NotBlank
#Size(max = 120)
private String password;
#Column(nullable = false)
private String givenName;
#Column(nullable = false)
private String surname;
private String birthday;
private String streetAddress;
private String city;
private String postalCode;
#Column(updatable = false, nullable = false)
private String email;
private String phoneNumber;
#CreationTimestamp
private Timestamp timestamp;
private Double balance;
private Integer bonuspoints;
private String role;
protected Customer() {
}
public Customer(String username,String password, String givenName, String surname, String birthday, String streetAddress, String city,
String postalCode, String email, String phoneNumber, Double balance, Integer bonuspoints, String role) {
this.username = username;
this.password = password;
this.givenName = givenName;
this.surname = surname;
this.birthday = birthday;
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
this.email = email;
this.phoneNumber = phoneNumber;
this.balance = balance;
this.bonuspoints = bonuspoints;
this.role = role;
}
#Override
public String toString() {
return ("Benutzername: "+username+ "Passwort: "+password+ "Vorname: " + givenName + " Nachname: " + surname +
" Geburtstag: " + birthday + " Straße: "+ streetAddress + " Stadt: " + city + " Postleitzahl: " +
postalCode + " E-Mail-Adresse: " + email+ " Telefonnummer: " + phoneNumber + "Kontostand: " + balance +
" Bonuspunkte: " + bonuspoints+" Rolle:"+role);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public Long getId() {
return id;
}
public String getGivenName() {
return givenName;
}
public String getSurname() {
return surname;
}
public String getBirthday() {
return birthday;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Timestamp getTimestamp() {
return timestamp;
}
public Integer getBonuspoints() {
return bonuspoints;
}
public Double getBalance() {
return balance;
}
public String getRole() {
return role;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public void setCity(String city) {
this.city = city;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public void setBonuspoints(Integer bonuspoints) {
this.bonuspoints = bonuspoints;
}
public void setRole(String role) {
this.role = role;
}
}
**
Can you pls give me tipps how I do it the right way?
in your build() method, you are passing Box, so it only knows the type as Object.
public static UserDetailsImpl build(Box<Object> user)
when you try to access it, you are trying to access the methods from type Customer, which it will not have any clue what methods are associated with Customer object. (user reference will only know about Box class methods)
so, what you need to do is change Box<Object> to Box<Customer> and then access the Customer's methods using
user.get().getId() etc.
here user.get() will return the underlying type object and you will have access to its methods.
or what you can also do is if you want the generic type to be a specific instance type, you can change your Box class implementation to be (extends T type to an instance of that class), for e.g. Customer in your case. (you ca create an interface or abstract class that will have methods that you are trying to use)
public class Box< T extends Customer>
public class Box<T extends CustomerInterface> etc.
When I post the data that time getting this error
Cannot invoke "com.helpmydesk.Repo.UserRepo.save(Object)" because "this.userRepo" is null
at com.helpmydesk.InterFaceAndService.ServiceClass.execute(ServiceClass.java:17) ~[classes/:na]
at com.helpmydesk.ControllerClass.execute(ControllerClass.java:27) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
Main Class
#EnableJpaRepositories("package com.helpmydesk.Repo.UserRepo")
#SpringBootApplication
public class HelpmydeskApplication {
public static void main(String[] args) {
SpringApplication.run(HelpmydeskApplication.class, args);
}
}
Controller Class
#Controller
public class ControllerClass {
#Autowired
private InterfaceClass interfaceClass;
public ControllerClass(InterfaceClass interfaceClass) {
this.interfaceClass = interfaceClass;
}
#PostMapping("/doregister")
public User execute(#RequestBody User user) {
return this.interfaceClass.execute(user);
}
#RequestMapping("/")
public String home() {
return "home";
}
#RequestMapping("/singup")
public String singup() {
return "singup";
}
}
Repository Class
#Repository
public interface UserRepo extends CrudRepository<User, Integer> {
}
interface Class
public interface InterfaceClass {
public User execute(User user);
}
Service Class
#Service
public class ServiceClass implements InterfaceClass {
private UserRepo userRepo;
public User execute(User user) {
this.userRepo.save(user);
return user;
}
}
User Class
#org.hibernate.annotations.Entity
#Table(name = "USER")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int id;
private String name;
#Column(unique = true)
private String email;
private String password;
private String role;
private boolean enabled;
private String imageUrl;
#Column(length = 500)
private String about;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private java.util.List<Blog> blogs = new ArrayList<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + ", role=" + role
+ ", enabled=" + enabled + ", imageUrl=" + imageUrl + ", about=" + about + "]";
}
}
enter image description here
You don't have #Autowired on your UserRepo variable. You can add it; the better fix is to eliminate field injection and use an ordinary constructor. Spring will provide all of the necessary dependencies when it calls the constructor, it makes testing much easier, and it prevents problems of this sort.
you should add #Autowired in your service class before ligne UserRepo userRepo
because userRepo must be injected before using it
I am working on a Spring Boot project and decided to use MongoDB . I just want to generate sequence number in MongoDB. So even if 100s of different clients trying to do that, I do not want to conflict any generated number. Is there any way to do that ?
Also I tried to make something like this :
SequenceNumber sequenceNumber;
String SEQUENCE_NAME = "example";
sequenceNumber = mongoOperations.findAndModify(query(where("_id").is(SEQUENCE_NAME)),
new Update().inc("number", 1), options().returnNew(true).upsert(true),
SequenceNumber.class);
return sequenceNumber.getNumber();
Is this correct ?
Thanks for answers !
https://www.javaprogramto.com/2019/05/spring-boot-mongodb-auto-generated-field.html
First, create a collection that will store the auto-incremented value in it. This can be created using either the mongo shell or MongoDB Compass
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "database_sequences")
public class DatabaseSequence {
#Id
private String id;
private long seq;
public DatabaseSequence() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getSeq() {
return seq;
}
public void setSeq(long seq) {
this.seq = seq;
}
}
Let’s then create a users_db collection. This collection stores the users that are being used.
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "users_db")
public class User {
#Transient
public static final String SEQUENCE_NAME = "users_sequence";
#Id
private long id;
private String firstName;
private String lastName;
private String email;
public User() { }
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long 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;
}
#Override
public String toString() {
return "User{" + "id=" + id + ", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}';
}
Here what I'm trying to do, accessing data with RestControllers from SQL DB,
code is compiling and running fine (Tomcat started on port(s): 8081 (http) with context path '') but whenever I'm trying to access the mapping from postman on http://localhost:8081/getAllStudents, I'm getting error
{"timestamp":"2018-06-09T11:03:59.136+0000","status":404,"error":"Not Found","message":"No message available","path":"/getAllStudents"}
/**Spring boot app**/
package com.akshay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan
#EnableJpaRepositories
#EnableAutoConfiguration
public class StartLearnApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(StartLearnApplication.class, args);
}
}
/**CONTROLLER**/
package com.akshay.spring.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.akshay.spring.dtos.StudentDTO;
import com.akshay.spring.services.StudentService;
#RestController
#RequestMapping("/api")
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/getAllStudents")
public List<StudentDTO> getAllStudents() {
return studentService.getAllStudents();
}
#GetMapping("/getStudentByRollNumber")
public StudentDTO getStudentBy(#RequestParam(name="rollNumber") String rollNumber) {
return studentService.getStudentBy(rollNumber);
}
#PostMapping("/saveStudent")
public StudentDTO saveStudent(#RequestBody StudentDTO studentDTO) {
return studentService.saveStudent(studentDTO);
}
#PostMapping("/deleteStudentByRollNumber")
public void deleteStudentBy(#RequestParam(name="rollNumber")String rollNumber) {
studentService.deleteStudentBy(rollNumber);
}
}
/**Service Interface**/
package com.akshay.spring.services;
import java.util.List;
import com.akshay.spring.dtos.StudentDTO;
public interface StudentService {
List<StudentDTO> getAllStudents();
StudentDTO getStudentBy(String rollNumber);
StudentDTO saveStudent(StudentDTO studentDTO);
void deleteStudentBy(String rollNumber);
}
/**Service Impl**/
package com.akshay.spring.serviceImpls;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.akshay.spring.dtos.StudentDTO;
import com.akshay.spring.models.StudentModel;
import com.akshay.spring.repositories.StudentRepository;
import com.akshay.spring.services.StudentService;
#Service
public class StudentServiceImpl implements StudentService {
#Autowired
StudentRepository studentRepository;
#Override
public List<StudentDTO> getAllStudents() {
List <StudentModel> studentsModelList = studentRepository.findAll();
List <StudentDTO> studentDTOList = null;
for(StudentModel student: studentsModelList) {
studentDTOList.add(convertModelToDTO(student));
}
return studentDTOList;
}
#Override
public StudentDTO getStudentBy(String rollNumber) {
return convertModelToDTO(studentRepository.getStudentByRollNumber(rollNumber));
}
#Override
public StudentDTO saveStudent(StudentDTO studentDTO) {
studentRepository.save(convertDTOToModel(studentDTO));
return studentDTO;
}
#Override
public void deleteStudentBy(String rollNumber) {
studentRepository.deleteStudentByRollNumber(rollNumber);
}
private StudentDTO convertModelToDTO(StudentModel student) {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setAddress(student.getAddress());
studentDTO.setEmailId(student.getEmailId());
studentDTO.setFathersName(student.getFathersName());
studentDTO.setFirstName(student.getFirstName());
studentDTO.setId(student.getId());
studentDTO.setLastName(student.getLastName());
studentDTO.setMothersName(student.getMothersName());
studentDTO.setPhoneNumber(student.getPhoneNumber());
studentDTO.setRollNumber(student.getRollNumber());
studentDTO.setStandard(student.getStandard());
return studentDTO;
}
private StudentModel convertDTOToModel(StudentDTO student) {
StudentModel studentModel = new StudentModel();
studentModel.setAddress(student.getAddress());
studentModel.setEmailId(student.getEmailId());
studentModel.setFathersName(student.getFathersName());
studentModel.setFirstName(student.getFirstName());
studentModel.setId(student.getId());
studentModel.setLastName(student.getLastName());
studentModel.setMothersName(student.getMothersName());
studentModel.setPhoneNumber(student.getPhoneNumber());
studentModel.setRollNumber(student.getRollNumber());
studentModel.setStandard(student.getStandard());
return studentModel;
}
}
/**Table Model**/
package com.akshay.spring.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student_details")
public class StudentModel {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
#Column(name = "id")
Long id;
#Column(name = "roll_number")
String rollNumber;
#Column(name = "first_name")
String firstName;
#Column(name = "last_name")
String lastName;
#Column(name = "standard")
String standard;
#Column(name = "phone_number")
String phoneNumber;
#Column(name = "email_id")
String emailId;
#Column(name = "fathers_name")
String fathersName;
#Column(name = "mothers_name")
String mothersName;
#Column(name = "address")
String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
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 getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFathersName() {
return fathersName;
}
public void setFathersName(String fathersName) {
this.fathersName = fathersName;
}
public String getMothersName() {
return mothersName;
}
public void setMothersName(String mothersName) {
this.mothersName = mothersName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return "StudentDTO [id=" + id + ", rollNumber=" + rollNumber + ", firstName=" + firstName + ", lastName="
+ lastName + ", standard=" + standard + ", phoneNumber=" + phoneNumber + ", emailId=" + emailId
+ ", fathersName=" + fathersName + ", mothersName=" + mothersName + ", address=" + address + "]";
}
}
/**DTO**/
package com.akshay.spring.dtos;
public class StudentDTO {
Long id;
String rollNumber;
String firstName;
String lastName;
String standard;
String phoneNumber;
String emailId;
String fathersName;
String mothersName;
String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
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 getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFathersName() {
return fathersName;
}
public void setFathersName(String fathersName) {
this.fathersName = fathersName;
}
public String getMothersName() {
return mothersName;
}
public void setMothersName(String mothersName) {
this.mothersName = mothersName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return "StudentDTO [id=" + id + ", rollNumber=" + rollNumber + ", firstName=" + firstName + ", lastName="
+ lastName + ", standard=" + standard + ", phoneNumber=" + phoneNumber + ", emailId=" + emailId
+ ", fathersName=" + fathersName + ", mothersName=" + mothersName + ", address=" + address + "]";
}
}
/**JPA repository**/
package com.akshay.spring.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.akshay.spring.models.StudentModel;
public interface StudentRepository extends JpaRepository<StudentModel, Long> {
StudentModel getStudentByRollNumber(String rollNumber);
void deleteStudentByRollNumber(String rollNumber);
}
I think your request mapping needs to be : http://localhost:8081/api/getAllStudents
I have done this is the past with mySQL but I need to use Oracle:
This is a very simple register user:
application.properties
#Oracle database setup
spring.datasource.url=jdbc:oracle:thin:#999.999.999.11:1521:d3SID
spring.datasource.username=userName
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
server.port = 4000
UserInformation model
#Entity
public class UserInformation {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "firstName")
#Min(2) #Max(15)
#NotNull
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userName")
private String userName;
#Column(name = "password")
private String password;
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 getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserInformation)) {
return false;
}
UserInformation that = (UserInformation) o;
return id.equals(that.id);
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return "Applicant{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", userName='" + userName + '\'' + ", password='" +
password + '\'' + '}';
}
}
JPA repo
public interface UserLoginRepo extends JpaRepository<UserInformation, Long> {}
Controller method
#RequestMapping(value = "/register", method = RequestMethod.POST)
public UserInformation registerUser(#RequestBody UserInformation user){
return userService.save(user);
}
When I run SELECT * FROM USERINFORMATION; nothing displays.
From my understanding I should not need to set up JPA config since I am doing it in applications.properties.
Did you check if the UserInformation object is coming from request body? As I know you shouldn't use "#RequestBody", just put "UserInformation user" must be in the parameters.