I am trying to implement a daoImpl in a Spring JPA applicacion.
I have this classes.
Dao
package com.oxygen.backendoxygen.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.oxygen.backendoxygen.model.Noticia;
@Repository
public interface NoticiaDao extends JpaRepository<Noticia, Long>, NoticiaDaoCustom {
}
Custom Dao:
package com.oxygen.backendoxygen.dao;
import java.util.List;
import com.oxygen.backendoxygen.model.Noticia;
public interface NoticiaDaoCustom {
List<Noticia> getUltimasNoticias();
}
And the impl of the custom Dao:
package com.oxygen.backendoxygen.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.oxygen.backendoxygen.dao.NoticiaDao;
import com.oxygen.backendoxygen.model.Noticia;
public abstract class NoticiaDaoCustomImpl implements NoticiaDao {
@PersistenceContext
EntityManager entityManager;
@SuppressWarnings("unchecked")
@Override
public List<Noticia> getUltimasNoticias () {
Query query = entityManager.createNativeQuery("SELECT em.* FROM spring_data_jpa_example.employee as em "
"WHERE em.firstname LIKE ?", Noticia.class);
query.setParameter(1, "parametro");
return query.getResultList();
}
}
Controller class:
package com.oxygen.backendoxygen.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.oxygen.backendoxygen.dao.NoticiaDao;
import com.oxygen.backendoxygen.model.Noticia;
@RestController @CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/rest")
public class NoticiaController {
@Autowired
NoticiaDao noticiaDao;
@GetMapping("/noticias")
public List<Noticia> getAllNoticias() {
return noticiaDao.findAll();
}
@GetMapping("/noticias/{id}")
public ResponseEntity<Noticia> getNoticiabyId (@PathVariable(value = "id") Long idNoticia) {
Noticia noticia = noticiaDao.getById(idNoticia);
return ResponseEntity.ok().body(noticia);
}
@PostMapping("/createNoticia")
public Noticia createNoticia(@Valid @RequestBody Noticia noticia) {
return noticiaDao.save(noticia);
}
@PutMapping("/updateNoticia/{id}")
public ResponseEntity<Noticia> updateNoticia(@PathVariable(value="id") Long idNoticia,
@Valid @RequestBody Noticia detallesNoticia) {
Noticia noticia = noticiaDao.getById(idNoticia);
noticia.setAutor(detallesNoticia.getAutor());
noticia.setContenido(detallesNoticia.getContenido());
noticia.setCategorias(detallesNoticia.getCategorias());
noticia.setFx_edicion_fx(detallesNoticia.getFx_edicion_fx());
noticia.setFx_publicacion_fx(detallesNoticia.getFx_publicacion_fx());
noticia.setImagen_destacada(detallesNoticia.getImagen_destacada());
noticia.setSubtitulo(detallesNoticia.getSubtitulo());
noticia.setTitulo(detallesNoticia.getTitulo());
final Noticia noticiaActualizado = noticiaDao.save(noticia);
return ResponseEntity.ok(noticiaActualizado);
}
@DeleteMapping("borrarNoticia/{id}")
public Map<String,Boolean> deleteNoticia(@PathVariable(value="id") Long idNoticia) {
Noticia noticia = noticiaDao.getById(idNoticia);
noticiaDao.delete(noticia);
Map<String, Boolean> response = new HashMap<>();
response.put("borrado", Boolean.TRUE);
return response;
}
}
When i try to run the application I have the next errors:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-10-14 11:39:03.306 ERROR 11992 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'noticiaController': Unsatisfied dependency expressed through field 'noticiaDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'noticiaDao' defined in com.oxygen.backendoxygen.dao.NoticiaDao defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! Reason: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.10.jar:5.3.10]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.10.jar:5.3.10]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.5.jar:2.5.5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.5.5.jar:2.5.5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) [spring-boot-2.5.5.jar:2.5.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) [spring-boot-2.5.5.jar:2.5.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) [spring-boot-2.5.5.jar:2.5.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) [spring-boot-2.5.5.jar:2.5.5]
at com.oxygen.backendoxygen.BackendOxygenApplication.main(BackendOxygenApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'noticiaDao' defined in com.oxygen.backendoxygen.dao.NoticiaDao defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! Reason: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.10.jar:5.3.10]
... 20 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! Reason: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!
at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.5.jar:2.5.5]
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source) ~[na:1.8.0_111]
at java.util.Iterator.forEachRemaining(Unknown Source) ~[na:1.8.0_111]
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Unknown Source) ~[na:1.8.0_111]
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.copyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.evaluate(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReferencePipeline.collect(Unknown Source) ~[na:1.8.0_111]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.5.jar:2.5.5]
at java.util.Optional.map(Unknown Source) ~[na:1.8.0_111]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:360) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.5.5.jar:2.5.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.10.jar:5.3.10]
... 30 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.oxygen.backendoxygen.dao.NoticiaDaoCustom.getUltimasNoticias()! No property getUltimasNoticias found for type Noticia!
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.5.jar:2.5.5]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.5.5.jar:2.5.5]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:218) ~[spring-data-jpa-2.5.5.jar:2.5.5]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:81) ~[spring-data-jpa-2.5.5.jar:2.5.5]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.5.jar:2.5.5]
... 52 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property getUltimasNoticias found for type Noticia!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.5.jar:2.5.5]
at java.util.concurrent.ConcurrentMap.computeIfAbsent(Unknown Source) ~[na:1.8.0_111]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.5.jar:2.5.5]
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source) ~[na:1.8.0_111]
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.copyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.evaluate(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReferencePipeline.collect(Unknown Source) ~[na:1.8.0_111]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.5.jar:2.5.5]
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source) ~[na:1.8.0_111]
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.copyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.AbstractPipeline.evaluate(Unknown Source) ~[na:1.8.0_111]
at java.util.stream.ReferencePipeline.collect(Unknown Source) ~[na:1.8.0_111]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:92) ~[spring-data-commons-2.5.5.jar:2.5.5]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.5.5.jar:2.5.5]
... 56 common frames omitted
What is wrong here. I have readed Spring docs and i dont find how to use JPA and custom methods for query.
Thanks in advance.
CodePudding user response:
In my opinion, in spring boot, there is no dao concept, instead it is a repository concept, for example ExampleRepository (which is the class that extends JpaRepository or crudRepository ) will correspond to Example (Entity)
for your purposes you can convert Example to whatever you want.
i am java develop on 1 year, so the answer may be not true.
update:
Controller
@RestController
@CrossOrigin("*")
public class ExampleControler {
private ExampleRepository exampleRepository;
public ExampleControler(ExampleRepository exampleRepository) {
this.exampleRepository = exampleRepository;
}
@DeleteMapping("/dd")
public void deleteAll() {
exampleRepository.deleteAll();
}
}
Entity
@Entity
@Data
@Table(name = "example")
@AllArgsConstructor
@NoArgsConstructor
public class Example {
@Id
@Column(name = "example1")
private Integer example1;
@Column(name = "example2")
private Integer example2;
}
Repository
@Repository
public interface ExampleRepository extends JpaRepository<Example, Integer> {
}
that is the basic architecture of spring boot project, you probably know. in application.properties you can add code blow to check query
JpaRepository<Example, Integer>
parameter is Entity, from this Entity, you can convert Class you want
CodePudding user response:
Your NoticiaDaoCustomImpl
class is abstract
, so Spring will never be able to create an instance of that class. Remove abstract and add @Component
on top of that class.
@Component
is an annotation that allows Spring to automatically detect custom beans.
Check here from more information about @Component
And this is the definition for abstract
class:
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
Read more about abstract
classes here.