Lombok not recognizing getters and setters - java

I am trying to set up lombok in my sts.
So far I have done these steps:
I downloaded the lambok jar file.
I ran the file and specified the path for sts.exe and then clicked on install.
I have added the required dependencies in my pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
I have also edited my sts.ini file. After installation of lambok.jar following line was already there at the end pf the file
-javaagent:E:\JAVA SOFTWARES\spring-tool-suite-3.9.8.RELEASE-e4.11.0-win32-x86_64\sts-bundle\sts-
3.9.8.RELEASE\lombok.jar
so I moved it next to
-vmargs
Then, I cleaned my project. I have also updated my project. Closed sts and then ran my application again. But it is still not recognizing the getters in my file. It produces the following error.
The method getFirstname() is undefined for the type Student
Student.java:
package com.crud.msstudent.models;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
#Getter
#Setter
#Accessors(chain=true)
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#NotEmpty(message = "First name is required")
private String firstname;
#NotEmpty(message = "Last name is required")
private String lastname;
#Column(nullable = true, name = "email")
private String email;
}
The error is being shown in my StudentController.java file. Following is some of the code:
#PutMapping(value="/students/{id}")
public Student updateStudent(#PathVariable("id") #Min(1) int id, #Valid
#RequestBody Student newstd) {
Student stdu = studentservice.findById(id)
.orElseThrow(()->new
StudentNotFoundException("Student with "+id+" is Not Found!"));
stdu.setFirstname(newstd.getFirstname());
stdu.setLastname(newstd.getLastname());
stdu.setEmail(newstd.getEmail());
return studentservice.save(stdu);
}
#DeleteMapping(value="/students/{id}")
public String deleteStudent(#PathVariable("id") #Min(1) int id) {
Student std = studentservice.findById(id)
.orElseThrow(()->new
StudentNotFoundException("Student with "+id+" is Not Found!"));
studentservice.deleteById(std.getId());
return "Student with ID :"+id+" is deleted";
}
Please tell me what am I missing?

If you're using STS you might be missing the plugin required for it. For further details please refer to the Lombok site on how to install it.

If mvnw.cmd clean compile command works normally, try project reloading.
Right click your project folder in Package Explorer > Maven > Update Project

Does this help (source):
To include lombok as a 'provided' dependency, add it to your block like so:
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
JDK9+ with module-info.java
The configuration of the compiler plug-in should contain the following:
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</path>
</annotationProcessorPaths>

are you using Eclipse IDE? in some case, you have to update the project explicitly in eclipse.
better to go without using lombok
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#NotEmpty(message = "First name is required")
private String firstname;
#NotEmpty(message = "Last name is required")
private String lastname;
#Column(nullable = true, name = "email")
private String email;
public Student()
{
}
public Student(int id,String firstname,String lastname,String email)
{
this.id=id;
this.firstname=firstname;
this.lastname=lastname;
this.email=email
}
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;
}

Related

Javax validation inside of list

So I have a class and a field that is list of strings and I want to validate every one of them, but it's not working, I tried this and this didn't work out:
public class Info {
#NotNull
#NotEmpty
private List<#Email(message = "uncorrect email") String> emails;
}
I also tried this and it didn't work:
public class Info {
#NotNull
#NotEmpty
private #Valid List<#Email(message = "uncorrect email") String> emails;
}
But when it's just one String it works fine.
public class Info {
#NotNull
#NotEmpty
private #Email(message = "uncorrect email") String email;
}
How can I achieve what I want?
Latest versions of hibernate validator support it. You can go with the following changes to achieve the desired validation behaviour.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
</dependencies>
Java Bean
import java.util.List;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class Info {
#NotNull
#NotEmpty
private List<#Email(message = "List contain atleast one incorrect email") String> emails;
#NotNull
#NotEmpty
#Email(message = "incorrect email")
private String email;
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Info [emails=" + emails + ", email=" + email + "]";
}
}
Adding the #Valid
#PostMapping("/post")
public void post(#RequestBody #Valid Info info) {
System.out.println(info);
}

rest api return duplicate values in postman and spring boot h2

I am new spring boot developer and i am trying to develope and rest api . when I do it ,I get and issues that my api return two duplicated response in postman .But i haven't code anythiong to get duplicated valuese in my code . the one of duplicate values is my model clase variable and athor one is table's attribute name .
below response in postman
model class
public class person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY )
private Long id;
#Column(name = "name")
private String Name ;
#Column(name ="surname")
private String Surname;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
}
repository
#Repository
public interface personRepository extends JpaRepository<person,Long> {
}
controller
#RestController
#RequestMapping("/person")
public class personController {
#Autowired
private personRepository repository;
public personController(personRepository repository) {
this.repository = repository;
}
#GetMapping("/view/list/person")
private List<person> viewperson() {
return repository.findAll();
}
#PostMapping("/insert/person")
private person savePerson(#RequestBody person obj) {
return repository.save(obj);
}
#DeleteMapping("/delete/{id}")
private void delete(#PathVariable Long id) {
repository.deleteById(id);
}
}
application.properties
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialec
t
The problem is that you're not following the proper conventions in your naming strategy.
Due to this, Jackson doesn't know that your getters (getSurname(), getName()) are referencing the fields Surname and Name. That's why it serializes both your fields and your getters separately to JSON.
To fix this, you can follow the Java naming conventions and use a lowercase letter for the first character of your fields.
For example:
#Column(name = "name")
private String name; // Change this
#Column(name ="surname")
private String surname; // Change this
This will change your JSON output to:
{
"id": 1,
"name": "bryan",
"surname": "Nicky"
}
If you want to keep your JSON with capital letters, you can use the #JsonProperty annotation:
#JsonProperty("Name") // Add this
#Column(name = "name")
private String name;
#JsonProperty("Surname") // Add this
#Column(name ="surname")
private String surname;
Unrelated to your question, but according to those naming conventions, your classes should start with a capital (eg. Person, PersonController, PersonRepository, ...).

I put a validation in the name attribute but it dosn't work

I follow a spring boot tutorial and I can't solve this problem because the tutorial is not detailed enough
this is the User model class code :
package com.example.user;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
public class User {
private Integer id;
#Size(min=2, message="Name should have atleast 2 characters")
private String name;
private Date birthDate;
protected User() {
}
public User(Integer id, String name, Date birthDate) {
super();
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
//getters and setters
}
this is the userResource code for the post mapping method :
#PostMapping("/users")
public ResponseEntity<Object> createUser(#Valid #RequestBody User user) {
User savedUser = service.save(user);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId()).toUri();
return ResponseEntity.created(location).build();
}
I solve the problem :
The hibernate validator dependacy was missed so I add it to the POM and everything works fine
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>

No qualifying bean of type 'com.jpa.dao.UserRepository' available

I am trying String JPA for the first time.
I was following a Youtube video by Durgesh Sir.
This is the error
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jpa.dao.UserRepository' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1177)
at com.jpa.demo.BootjpaApplication.main(BootjpaApplication.java:13)
Following are my files
BootjpaApplication.java (which contains main)
package com.jpa.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.jpa.dao.UserRepository;
import com.jpa.entities.user;
#SpringBootApplication
public class BootjpaApplication {
public static void main(String[] args) {
ApplicationContext context= SpringApplication.run(BootjpaApplication.class, args);
UserRepository userrepo= context.getBean(UserRepository.class);
user user=new user();
user.setName("Varun Dhawan");
user.setCity("Paris");
user.setStatus("happy");
user user1= userrepo.save(user);
System.out.println(user1);
}
user.java (there are 4 variables. id is auto generated. Other 3 have getters and setters.
package com.jpa.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class user {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String name;
private String city;
private String status;
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 getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public user(int id, String name, String city, String status) {
super();
this.id = id;
this.name = name;
this.city = city;
this.status = status;
}
public user() {
super();
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return "user [id=" + id + ", name=" + name + ", city=" + city + ", status=" + status + "]";
}
}
UserRepository.java
package com.jpa.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.jpa.entities.user;
#Repository
public interface UserRepository extends JpaRepository<user,Integer> {
}
Application.properties
spring.datasource.name=jpa
spring.datasource.url=jdbc:mysql://localhost:3306/jpa
spring.datasource.username=root
spring.datasource.password=root#123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
Thank you!
It looks like your packages are not scanned properly.
Can you please try adding #SpringBootApplication(scanBasePackages = "com.jpa") instead of #SpringBootApplication.
just create a single package(forget about coupling for a bit and do that). Then put all the classes(POJO , Main) and Interface(UserRepository) in side that package and re-start your project. It will work.
your package structure should be like this,
com.spring
com.spring.DAO
com.spring.Model
com.spring.View
com.spring.Controller
In pom.xml file checks for hibernate and JPA configuration
Same bug occur in my application
I resolve it by adding configuration
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Thank you !
I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.
#EnableJpaRepositories("com...jpa")
#EntityScan("com...jpa")
After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.
#ComponentScan("com...service")
This solved my issues.

Produce JSON by RESTful web service in Spring Boot?

My problem: I don't returns Json but an array.
So, I will wish Json return:
My repository interface:
public interface SuiRepository extends JpaRepository<Folder, Integer>{
#Query("...")
public List<Folder> data();
}
My method:
#Override
public List<Folder> getFolder(){
List<Folder> s = folderRepository.data();
return s;
}
My Rest Service:
#RequestMapping(value="/folders", method=RequestMethod.GET, produces="application/json", consumes="application/json")
#ResponseBody
public List<Folder> getFolders() {
return iUd.getFolders();
}
My Folder class
Entity
public class Folder implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int idFolder;
private String comments;
#ManyToOne
#JoinColumn(name="IdFile")
private File file;
#ManyToOne
#JoinColumn(name="username")
private User user;
**Getters&Setters...**
}
The current return:
[["Ban","dee","dede#gmail.com",1,"xx","Emb"],["Cin","mis","sse#gmail.com",1,"yy","Ns"]]
Thanks!
You can use a constructor annotated with #JsonCreator in you entity:
Ex
...
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
String phone;
String password;
#JsonCreator
public User(#JsonProperty("name") String name,
#JsonProperty("phone") String phone) {
this.name = name;
this.phone = phone;
}
...
Could you please check you have the following dependency in your pom.xml ?
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.6.3</version>
</dependency>
Also you can have more information about how Spring boot handles Java object to JSON on spring boot website : https://spring.io/guides/gs/rest-service/
The Greeting object must be converted to JSON. Thanks to Spring’s HTTP
message converter support, you don’t need to do this conversion
manually. Because Jackson 2 is on the classpath, Spring’s
MappingJackson2HttpMessageConverter is automatically chosen to convert
the Greeting instance to JSON.
Try this one in controller :
#RequestMapping(value="/folders", method= RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Folder> getFolders()
{
HttpStatus httpStatus = HttpStatus.OK;
List<Folder> listFol=iUd.getFolders();
return new ResponseEntity<HawkeyesResponse>(listFol,httpStatus);
}
In class level add this annotation :
#RestController

Categories

Resources