Spring lombok #AllArgsConstructor is not working - spring

I am using lombok but looks like #AllArgConstructor is not working when i'm create object of that class Sts is showing as
Description Resource Path Location Type
The constructor Employee(String, String, String[]) is undefined EmployeeController.java /spring-solr/src/main/java/com/ajay/solr/controller line 21 Java Problem
package com.ajay.solr.model;
import org.apache.solr.client.solrj.beans.Field;
import org.springframework.data.annotation.Id;
import org.springframework.data.solr.core.mapping.SolrDocument;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#SolrDocument(collection = "Employee")
public class Employee {
#Id
#Field
private int id;
#Field
private String name;
#Field
private String[] address;
}
And the class where I am using is
package com.ajay.solr.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.ajay.solr.model.Employee;
import com.ajay.solr.repository.EmployeeRepository;
#RestController
public class EmployeeController {
#Autowired
private EmployeeRepository empRepository;
public void addEmployees() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(373,"Sunil",new String[] {"Hyderabad","Gazipur"}));
employees.add(new Employee(374,"Ajay",new String[] {"AnjaiyahNagar","Maharajganj"}));
employees.add(new Employee(375,"Praveen",new String[] {"SRNagar","Baliya"}));
}
}

If you are using STS. You must have Lombok installed in your Eclipse by running lombok-xyz.jar
Please Try the Following the Steps:
1.Include pom in Maven .
2. Exit/Shutdown STS
3. Find lombok Jar from https://projectlombok.org/download
4.From Command Prompt/Shell java -jar lombok-1.x.y.jar
This will open a pop-up screen, then specify your path for STS/Eclipse.exe
Hit the install button
Start STS/Eclipse
(If you are still facing the issue, try updating your project: right-click on project -> Maven -> Update Project and the errors will disappear.)

annotationProcessor 'org.projectlombok:lombok'
compileOnly 'org.projectlombok:lombok'
Adding this in my build.gradle file, worked.

Related

Annotation #Profile() doesn't work in Spring (not Boot) project

Annotation #Profile doesn't work or works wrongly. I want to get 7 beans: first-sixth and firstConfig.
In package app.a I created three classes.
package app.a;
import lombok.*;
#Data
public class First {
private Second second;
private Third third;
}
package app.a;
import lombok.*;
import org.springframework.stereotype.*;
#Data
#Component
public class Second {
}
package app.a;
import lombok.*;
import org.springframework.stereotype.*;
#Data
#Component
public class Third {
}
In package app.firstConfig I created config class "FirstConfig", annotated with #Configuration.
package app.firstConfig;
import app.a.*;
import app.b.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.*;
import org.springframework.context.annotation.*;
#Configuration
#Profile("one")
#ComponentScan(basePackages = "app.*")
public class FirstConfig {
#Bean
public First first(Second second, Third third) {
First first = new First();
first.setSecond(second);
first.setThird(third);
return first;
}
}
In package app.c I created two classes.
package app.c;
public class Eight {
}
package app.c;
import lombok.*;
#Data
public class Seventh {
private Eight eight;
}
And in package app.secondConfig I created configure class with annotation #Configuration.
package app.secondConfig;
import app.c.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.*;
import org.springframework.context.annotation.*;
#Configuration
#Profile("two")
public class SecondConfig {
#Autowired
private ApplicationContext applicationContext;
#Bean
public Seventh seventh(){
Seventh seventh = new Seventh();
seventh.setEight(applicationContext.getBean(Eight.class));
return seventh;
}
}
My main class:
package app;
import app.firstConfig.*;
import org.springframework.context.*;
import org.springframework.context.annotation.*;
import java.util.*;
public class Main {
static ApplicationContext applicationContext = new AnnotationConfigApplicationContext(FirstConfig.class);
public static void main(String[] args) { Arrays.stream(applicationContext.getBeanDefinitionNames()).forEach(System.out::println);
}
}
In EditConfigurations of IntelijIdea I wrote "-Dspring.profiles.active=one".
But in result I got these beans:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
Process finished with exit code 0
But if I delete annotation #Profile("one") in FirstConfig I get right result.
package app.firstConfig;
import app.a.*;
import app.b.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.*;
import org.springframework.context.annotation.*;
#Configuration
#ComponentScan(basePackages = "app.*")
public class FirstConfig {
#Bean
public First first(Second second, Third third) {
First first = new First();
first.setSecond(second);
first.setThird(third);
return first;
}
}
Result:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
firstConfig
second
third
fifth
sixth
first
fourth
What I forgot to do or configurate???
How to use annotation #Profile() rightly???
Seems like setting active profile does not work properly. You can add it to your propeties file as well and if you look at the top of the spring log output it usually tells you which profile has been activated (within the first 10 lines). If the default profile is loaded and you've added the line into config, try setting it as an environment variable. If it works its likely the properties file you've specified is not being picked up. Try it and update the question with any log output your seeing in relation to the active profile loaded.

Lombok annotation Value. Cannot find method 'value'

#Repository
#AllArgsConstructor
public class DataProvider {
#Value("${db.url}")
private String dbUrl;
}
IDE - idea
Plugin installed in IDE,dependecy installed
import # value from import org.springframework.beans.factory.annotation.Value;
it works
1- verifier your import, maybe you imported value from lombok, and it's wrong,so change your import:
import lombok.Value;
to:
import org.springframework.beans.factory.annotation.Value;

MongoRepository Delete Method

Good afternoon fellow coders!
I have spent the last hour looking to delete a single document from my mongo "testCollection". I would like to make use of the MongoRepository delete / deleteAll methods. However, it does not remove the document. It persists regardless of how many times I run the test class method. No errors are reported and the user has readWrite permissions in the database. I am able to run the mongo command to remove the newly created test document.
I have read about using the mongo template and create it for the deletion to be performed. I'm happy to do that but I would rather keep it as simple as possible.
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId;
#Data
#Document(collection = "testCollection")
public class TestClass {
#MongoId
private String id;
private String name;
public TestClass(String name) {
this.name = name;
}
}
Test Class Mongo Repository interface
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface TestClassRepository extends MongoRepository<TestClass, String> {
public List<TestClass> findAllByName(String name);
public void deleteAllByIdIn(List<TestClass> list);
}
Test Method
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
#RunWith(SpringRunner.class)
#TestPropertySource(value = {"classpath:application.properties"})
#AutoConfigureMockMvc
public class testClassTest {
#Autowired
private TestClassRepository testClassRepository;
#Test
public void crudTest() {
TestClass testObj = new TestClass("Test");
testClassRepository.save(testObj);
List<TestClass> testClassList = testClassRepository.findAllByName("Test");
Assert.assertEquals(1, testClassList.size());
TestClass test = testClassList.get(0);
testClassRepository.deleteAllByIdIn(testClassList);
// Fails this assertion: Found 1, expected 0.
Assert.assertEquals(0, testClassRepository.findAllByName("Test").size());
}
}
As anyone else experienced a similar issue? If so, how'd you go about resolving it?
Thanks!
Additions to original post:
Here is the mongo query generated by the MongoRepository. It appears that it is not actually adding the "remove" mongo command to the query. Query: { "name" : "Test"}, Fields: {}, Sort: {}
With a stroke of dumb luck I managed to figure out the issue. The problem was with the type of identifier annotation I was using. This explanation from another stackoverflow user (What is use of #MongoId in Spring Data MongoDB over #Id?) had me revisit this aspect of the model.
I switched the identifier annotation from #MongoId to #Id. Since I have both JPA and MongoDB annotations I needed to make sure I chose the one from the org.springframework.data.annotation package rather than the javax.persistance package.
Hope this explanation helps others!

In Spring boot application is #Component annotation optional for repo

I have created the basic application using Spring boot using JPA. I have added #AutoWired annotation for RatingRepo in RatingResource, but haven't added #Component annotation to RatingRepo
package com.example.demo;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.RatingsRateService.model.Rating;
import com.example.demo.RatingsRateService.model.UserRating;
#RestController
#RequestMapping("ratingsdata")
public class RatingResource {
#Autowired
RatingRepo repo;
/*
* #RequestMapping("/{movieId}") public Rating
* getRating(#PathVariable("movieId") String movieId) { return new
* Rating(movieId,7); }
*/
#RequestMapping("users/{userid}")
public UserRating getRating(#PathVariable("userid") int userid) {
List<Rating> ratings =repo.findByUserId(userid);
/*
* List<Rating> ratings = Arrays.asList(new Rating("1",4), new Rating("2",3),
* new Rating("3",2));
*/
System.out.println(ratings);
UserRating userRating = new UserRating();
userRating.setUserRating(ratings);
return userRating;
}
}
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.example.demo.RatingsRateService.model.Rating;
//to update the data in database , created the interd=face and will implement
//class,primary key
public interface RatingRepo extends JpaRepository<Rating, Integer>{
#Query(" from Rating where userid = ?1")
List<Rating> findByUserId( int userid);
}
. Still, it is working fine. Can you someone please explain why it is so? Or it is not needed to add #Component annotation for the repo?
first of there is #Repository annotation required not #Component
and #Repository also auto configure due to below:
Probably you are using spring boot
Spring Data repositories usually extend from the Repository or CrudRepository interfaces. If you are using auto-configuration, repositories will be searched from the package containing your main configuration class (the one annotated with #EnableAutoConfiguration or #SpringBootApplication) down.
ref: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-spring-data-jpa-repositories

Unable to inject dependency in Junit test

Having some trouble injecting a dependency in one of my JUnit test classes.
I believe the TestApplication is not package scanning or is not being loaded.
Code below:
package com.mitto.repositories;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.mitto.MittoApplicationTests;
import com.mitto.domain.User;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration( classes= { MittoApplicationTests.class } )
#TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
#DatabaseSetup("UserRepositoryTest.xml")
public class UserRepositoryTest {
#Autowired
UserRepository repository;
private static final long FACEBOOK_ID = 1234567;
#Test
public void getUserById() {
User user = repository.findOne(1L);
assertNotNull(user);
assertEquals( user.getFacebookId(), FACEBOOK_ID );
}
}
MittoApplicationTests.java
package com.mitto;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class MittoApplicationTests {
#Test
public void contextLoads() {
}
}
UserRepository.java
package com.mitto.repositories;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.mitto.domain.User;
#Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long>{
User findByFacebookId( long facebookId );
User findByAuthToken( String token );
}
I can't see anything wrong with this.
Sometimes, a working example is better than fixes.
Here is a working example:
First, in your configuration class
#SpringBootApplication
#ComponentScan(value = "com.mitto")
#EnableJpaRepositories(value = "com.mitto")
#EntityScan(basePackages = {"com.mitto.domain"}, basePackageClasses = {Jsr310JpaConverters.class})
public class MittoApplicationTests {
}
Second, in your test class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = MittoApplicationTests.class) // replace the #ContextConfiguration with #SpringBootTest
// rest of of your annotations ...
public class UserRepositoryTest {
#Autowired
UserRepository repository;
// your test cases
}
A Spring Boot application is just a Spring ApplicationContext, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. One thing to watch out for though is that the external properties, logging and other features of Spring Boot are only installed in the context by default if you use SpringApplication to create it.
Spring Boot provides a #SpringBootTest annotation which can be used as an alternative to the standard spring-test #ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests via SpringApplication.
Please read the documentation for more details:
SpringBootTest annotation
boot-features-testing

Resources