在Spring Boot上创建自定义findBy可以通过以下步骤实现:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CustomRepository<T, ID> extends JpaRepository<T, ID> {
// 添加自定义的查询方法
List<T> findByCustomField(String customFieldValue);
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String customField;
// 省略其他属性和方法
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;
@Repository
public class CustomRepositoryImpl<T, ID> implements CustomRepository<T, ID> {
private final EntityManager entityManager;
@Autowired
public CustomRepositoryImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public List<T> findByCustomField(String customFieldValue) {
TypedQuery<T> query = entityManager.createQuery("SELECT e FROM YourEntity e WHERE e.customField = :customFieldValue", YourEntity.class);
query.setParameter("customFieldValue", customFieldValue);
return query.getResultList();
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(repositoryBaseClass = CustomRepositoryImpl.class)
public class JpaConfig {
// 配置其他JPA相关的Bean
}
现在你可以在你的服务类或控制器中使用自定义的findBy方法了。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class YourService {
private final CustomRepository<YourEntity, Long> customRepository;
@Autowired
public YourService(CustomRepository<YourEntity, Long> customRepository) {
this.customRepository = customRepository;
}
public List<YourEntity> findByCustomField(String customFieldValue) {
return customRepository.findByCustomField(customFieldValue);
}
}
这样,你就可以在Spring Boot上创建自定义的findBy方法了。注意,上述示例中的CustomRepository和CustomRepositoryImpl是自定义的命名,你可以根据实际情况进行修改。
领取专属 10元无门槛券
手把手带您无忧上云