Custom MongoDB spring data repository - java

I want to implement custom repo with Spring data mongodb.
Application.java:
#SpringBootApplication
public class Application implements CommandLineRunner{
#Autowired
private CustomerRepositoryCustom repo;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println(this.repo.customMethod());
}
}
My custom repository CustomerRepositoryCustom.java
public interface CustomerRepositoryCustom {
List<Customer> customMethod();
}
Custom implementation CustomCustomerRepositoryImpl.java
public class CustomCustomerRepositoryImpl implements CustomerRepositoryCustom {
#Autowired
private MongoTemplate mongoTemplate;
#Override
public List<Customer> customMethod() {
return this.mongoTemplate.findAll(Customer.class);
}
}
Code Structure
-Application.java
dal
model...
repository
-CustomCustomerRepositoryImpl.java
-CustomerRepositoryCustom.java
When I try to build it, i get an error:
**Description**:
Field repo in socketApp.Application required a bean of type 'socketApp.dal.repository.CustomerRepositoryCustom' that could not be found.
**Action**:
Consider defining a bean of type 'socketApp.dal.repository.CustomerRepositoryCustom' in your configuration.

You have to make Spring aware of your repository. For a Spring Boot application this is typically done by adding this annotation to your application ...
#EnableMongoRepositories("com.package.path.to.repository")
.... thereby telling Spring Boot where to look for Mongo repositories and then let your interface extend org.springframework.data.mongodb.repository.MongoRepository.
For example:
public interface CustomerRepositoryCustom extends MongoRepository {
List<Customer> customMethod();
}
Alternatively, you could annotate your CustomCustomerRepositoryImpl with #Repository and ensure that it is in a package which is scanned by Spring Boot.

Related

How can I use the client side of soap in my spring boot project?

I'm working on a project right now and I want to use SOAP web service with dependency injection in my Spring Boot project, but I'm having a problem.
As you can see below, I'm injecting using #Autowired annotation, but it shows this problem:
Could not autowire. No beans of 'KNIKPSPublicSoap' type found.
#Service
#RequiredArgsConstructor
public class JobSeekerManager implements JobSeekerService {
private final JobSeekerDal jobSeekerDal;
#Autowired
private KNIKPSPublicSoap soapClientWS;
#Override
public void save(JobSeeker jobSeeker) {
//logica
this.jobSeekerDal.save(jobSeeker);
}
#Override
public List<JobSeeker> findAll() {
return this.jobSeekerDal.findAll();
}
}

Exclude JPA Spring boot - org.springframework.boot:spring-boot-starter-data-jpa' causes error in CRUDRepository when starting

My plan is having 1 code 2 different app. Only 1 app will connect to database and hava a transaction. I am having an error when starting my webapp in the application where it doesnt have any database , the only way is to exclude JPA dependencies. When starting the application , it throws an error
Parameter 2 of constructor in chat.ChatService required a bean of type 'chat.ChatLogRepository' that could not be found.
This is my spring boot application
#AllArgsConstructor
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class ApplicationDmz implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(chat.ApplicationDmz.class, args);
}
#Bean
RestOperations restOperationsDmz() {
return new RestTemplate();
}
}
This is my service calling the CRUDRepository
#AllArgsConstructor
#Component
public class ChatService {
#Getter
private SimpMessageSendingOperations template;
SimpUserRegistry userRegistry;
private ChatLogRepository chatLogRepository;
And this is my CRUDRepository
import org.springframework.data.repository.CrudRepository;
public interface ChatLogRepository extends CrudRepository<ChatLog, Long> {
}
I just want to fix the issue when starting my app with exclude JPA
Your test bet is to import your repository bean manually:
import org.springframework.context.annotation.Import;
#Import(ChatLogRepository.class)
This should go within a #Configuration class or your #SpringBootApplication class.

i want to create the non-web spring boot application

i want to create the non-web spring boot application. But i am getting following error
#SpringBootApplication
public class TaskApplication implements CommandLineRunner {
#Autowired
TaskService taskService;
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
taskService.print();
}
}
public interface TaskService {
public void print();
}
public class TaskServiceImpl implements TaskService {
#Override
public void print() {
System.out.println("sam");
}
}
properties:
spring.datasource.url=jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false&requireSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root#123
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.main.allow-bean-definition-overriding=true
##spring.jpa.hibernate.ddl-auto=update
error
***************************
APPLICATION FAILED TO START
***************************
Description:
Field taskService in com.example.task.TaskApplication required a bean of type 'com.example.task.service.TaskService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.task.service.TaskService' in your configuration.
#M. Deinum already explained in comments. You need to mark classes with #Service or #Component annotation to create the spring bean and autowired in main methods.
// mark it with service annotation.
#Service
public class TaskServiceImpl implements TaskService {
#Override
public void print() {
System.out.println("sam");
}
}
To understand why those annotation is necessary here please visit this link : #Component vs #Repository and #Service in Spring
you need to configure #EnableAutoConfiguration on main class and your TaskService must be annotated with #Service

Testing JPA Entities

I want to know how to write Junit test for Spring Repository classes.
As example :
class-AccountMoveActionDet
Jpa interface-AccountMoveActionDetlJpaRepository
And I want to test this repository class work or not.Spring Jpa support some methods like
List findAll();
deleteAll();
I wrote a class just like below:
#RunWith(SpringJUnit4ClassRunner.class)
public class AccountTypeMovementJpaRepositoryTest extends AbstractJpaTest {
#Autowired
AccountTypeMovementJpaRepository accountTypeMovementJpaRepository;
#Override
public void test() {
executeSqlScript("/fixtures/accountTypeMovementJpa.sql");
assertEquals("accountTypeMovementJpaRepository Test", accountTypeMovementJpaRepository.findAll().size(),
JdbcTestUtils.countRowsInTable(getJdbcTemplate(), "COF5REP"));
}
}
Error creating bean with name
'com.gayan.cmp.jparepositories.test.AccountTypeMovementJpaRepositoryTest':
Please help me to resolve this.
If you use spring-boot 1.4 and above the best place to start, Testing the JPA slice :
#RunWith(SpringRunner.class)
#DataJpaTest
public class UserRepositoryTests {
#Autowired
private TestEntityManager entityManager;
#Autowired
private UserRepository repository;
#Test
public void findByUsernameShouldReturnUser() {
this.entityManager.persist(new User("sboot", "123"));
User user = this.repository.findByUsername("sboot");
assertThat(user.getUsername()).isEqualTo("sboot");
assertThat(user.getVin()).isEqualTo("123");
}
}

Combine 2 Spring boot application

Just following Spring Guides http://spring.io/guides#gs I took gs-rest-service and gs-accessing-data-jpa. Now I want to combine them in one application, and that is where like more understanding of new org.springframework.boot.SpringApplication is needed.
In gs-rest-service config looks emazing, that is almost absent
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
gs-accessing-data-jpa is more like Spring XML JavaConfig based app.
#Configuration
#EnableJpaRepositories
public class CopyOfApplication {
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(H2).build();
}
// 2 other beans...
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(CopyOfApplication.class);
CustomerRepository repository = context.getBean(CustomerRepository.class);
//...
}
}
How to combine them?
Does it mean that I need to re-write SpringApplication.run now on more detailed level ?
In the Spring Boot application simply add the dependencies from the JPA sample (the ones which you don't already have.
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M7")
compile("org.springframework:spring-orm:4.0.0.RC1")
compile("org.springframework.data:spring-data-jpa:1.4.1.RELEASE")
compile("org.hibernate:hibernate-entitymanager:4.2.1.Final")
compile("com.h2database:h2:1.3.172")
testCompile("junit:junit:4.11")
}
or instead of this you could also use the spring boot starter project for Spring Data JPA. In that case the dependencies would look like the following.
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M7")
compile("org.springframework.boot:spring-boot-starter-data-jpa:0.5.0.M7")
compile("com.h2database:h2:1.3.172")
testCompile("junit:junit:4.11")
}
This will pull in all needed dependencies.
Next copy the CustomerRepository to the Spring Boot application. That basically should be everything you need. Spring Boot auto-configure now detects Spring Data JPA and JPA and will bootstrap hibernate, spring data for you.
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ApplicationContext context= SpringApplication.run(Application.class, args);
CustomerRepository repository = context.getBean(CustomerRepository.class);
//...
}
}

Categories

Resources