CrudRepository를 확장하는 Spring Boot
스프링 부트 앱에서 최대 절전 모드를 사용하고 있습니다.기본적인 CRUD 작업을 수행하기 위해 모든 모델 개체를 위한 새로운 CrudRepository를 만들고 있습니다.그들은 다음과 같이 보입니다.
@Repository
public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> {
}
하지만 저는 불평등이 있는 맞춤형 검색 쿼리와 같은 몇 가지 추가 작업을 항상 수행해야 합니다.저는 다음과 같은 패턴을 따릅니다.
@Repository
public class FoobarDao {
@PersistenceContext
EntityManager em;
public List<Foobar> findFoobarsByDate(Date date) {
String sql = "select fb from Foobar fb where createdDate > :date";
...
return query.getResultList();
}
}
제 질문은, 제가 이 두 개념을 하나의 수업으로 결합할 수 있을까요?저는 추상적인 수업으로 만들려고 노력했습니다.
@Repository
public abstract class FoobarCrudRepo extends CrudRepository<Foobar, Long> {
@PersistenceContext
EntityManager em;
public List<Foobar> findFoobarsByDate(Date date) {
String sql = "select fb from Foobar fb where createdDate > :date";
...
return query.getResultList();
}
}
하지만 스프링은 그것을 위한 콩을 만들지 않았습니다.
어떻게 하면 이 일을 해낼 수 있을까요?
감사합니다!
여러분이 이것을 성취할 수 있는 많은 방법들이 있습니다.만약 당신이 정말로 절대적인 통제가 필요하다면 이것을 시도하세요.
interface FoobarRepositoryCustom{
List<Foobar> findFoobarsByDate(Date date);
}
interface FoobarRepository extends CrudRepository<Foobar, Long>, FoobarRepositoryCustom
public class FoobarRespoitoryImpl implements FoobarRepositoryCustom{
@PersistenceContext private EntityManager em;
public List<Foobar> findFoobarsByDate(Date date) {
String sql = "select fb from Foobar fb where createdDate > :date";
...
return query.getResultList();
}
}
또한 더 간단한 경로로 이동할 수 있으며 메소드 이름을 기반으로 쿼리를 자동 생성할 수 있습니다.당신의 예에서 당신은 이것을 당신의 FoobarCrudRepo에 추가할 수 있고, Spring은 Foobar가 CreatedDate라는 속성을 가지고 있다고 가정하고 나머지를 해야 합니다.
List<Foobar> findByCreatedDateGreaterThan(Date date);
Spring이 메서드 이름을 기반으로 쿼리를 생성하는 방법에 대한 자세한 내용은 이 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ #distributories.sys-message.sys-creation을 참조하십시오.
여기서 문제는abstract
키워드
@Repository
public abstract class FoobarCrudRepo extends CrudRepository<Foobar, Long>
봄은 구체적인 수업이 아니면 수업을 위한 콩을 만들지 않습니다.그것이 당신이 그것을 위해 돈을 받는 이유입니다.
이게 제게 효과가 있었던 겁니다
@SpringBootApplication(scanBasePackages = { "com.myproject" })
@EnableJpaRepositories(basePackages="com.myproject.sprinbootapp.repository")
@EntityScan("com.myproject.sprinbootapp.model")
public class SpringbootAppWithDatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAppWithDatabaseApplication.class, args);
}
}
@Service
public class TopicService {
@Autowired
private TopicRepository topicRepository;
private List<Topics> topics = new ArrayList<Topics>();
public List<Topics> getAllTopics(){
List<Topics> listOfTopics = new ArrayList<Topics>();
topicRepository.findAll().forEach(listOfTopics::add);;
return listOfTopics;
}
}
@Entity
public class Topics {
@Id
private String id;
private String name;
public Topics(){
}
getters and setters...
}
public interface TopicRepository extends CrudRepository<Topics, String> {
}
우리는 JPA를 사용할 수 있습니다.EntityManager
직접 SQL 작업의 경우:
public interface VerificationsRepository extends
CrudRepository<Verification, Integer>,
DAOAccess
{ }
interface DAOAccess {
List findByEmail(String email);
}
class DAOAccessImpl implements DAOAccess {
@PersistenceContext private EntityManager em;
public List findByEmail(String email) {
String sql =
"select * from verifications where email = ?";
Query query = em.createNativeQuery(sql, Verification.class)
.setParameter(1, email);
return query.getResultList();
}
}
언급URL : https://stackoverflow.com/questions/30880927/spring-boot-extending-crudrepository
'programing' 카테고리의 다른 글
matplotlib(파이톤)에서 글꼴을 변경하는 방법은 무엇입니까? (0) | 2023.07.28 |
---|---|
Python Nose 가져오기 오류 (0) | 2023.07.28 |
각진 소재에서 스타일링 매트 선택 (0) | 2023.07.28 |
MySQL: 임의 항목 선택, 그러나 특정 항목에 대한 가중치 (0) | 2023.07.28 |
도커-업 vs 도커-업 --빌드 vs 도커-업 빌드 --캐시 없음 (0) | 2023.07.28 |