鉴于以下课程:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name="animalType",discriminatorType=DiscriminatorType.STRING)
@QueryExclude
public abstract class Animal {}
@Entity
@DiscriminatorValue("dog")
public class Dog {}
@Entity
@DiscriminatorValue("cat")
public class Cat {}
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式配置JPA存储库Animal吗?
我试过了
public interface AnimalRepository extends JpaRepository<Animal,Long>
Run Code Online (Sandbox Code Playgroud)
然而,这失败了:
java.lang.IllegalArgumentException:不是托管类型:Animal
有没有办法配置这个?
我希望能够执行以下任务:
@Autowired
private AnimalRepository repository;
public void doSomething()
{
Animal animal = repository.findById(123);
animal.speak();
}
Run Code Online (Sandbox Code Playgroud) 我有一个包(比方说packagesToScan)包含我希望持久注释的类@Entity.
在定义ApplicationContext配置时,我做了如下操作.
@Configuration
@EnableJpaRepositories("packagesToScan")
@EnableTransactionManagement
@PropertySource("server/jdbc.properties")
@ComponentScan("packagesToScan")
public class JpaContext {
...
// Other configurations
....
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(this.dataSource());
emf.setJpaVendorAdapter(this.jpaVendorAdapter());
emf.setPackagesToScan("packagesToScan");
emf.setJpaProperties(this.hibernateProperties());
return emf;
}
Run Code Online (Sandbox Code Playgroud)
在开发时,我有一些类packagesToScan不满足持久性要求(比如没有主键等),因此我不允许因为ApplicationContext安装失败而运行测试.
现在,
有什么方法可以扫描一些选定的类或忽略其中的一些类packagesToScan?
我正在使用spring-data-jpa和querydsl(3.2.3)
我有一个场景,我根据用户文件管理器/输入创建一组谓词.所有这些都来了BooleanExpression.
我的简化模型如下:
@Entity
public class Invoice {
@ManyToOne
private Supplier supplier;
}
@Entity
public class Supplier {
private String number;
}
@Entity
public class Company {
private String number;
private boolean active
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在努力解决的是这个问题:
SELECT * FROM Invoice WHERE invoice.supplier.number in (SELECT number from Company where active=true)
Run Code Online (Sandbox Code Playgroud)
所以基本上我需要以CollectionExpression类似格式的子查询来获取所有公司的数字并将其设置为in()表达式.
我的spring-data存储库实现CustomQueryDslJpaRepository了反过来扩展JpaRepository和QueryDslPredicateExecutor.
我希望答案是直截了当的,但我对querydsl很新,到目前为止还没有找到解决方案.
我试图从Spring Data查询中获得单个结果.我想从用户表中返回最大的ID.我希望它会很简单,但我有点失落.
到目前为止,基于这个相关的SO帖子,我得出结论,我需要使用a Specification来定义我的查询和Page结果,指定我想要检索的结果数.不幸的是,我收到了HibernateJdbcException数据访问异常.
我Specification/ Predicate应该相当简单并反映from User order by id:
Page<User> result =userRepository.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
query.orderBy(cb.desc(root.get("id")));
return query.getRestriction();
}
}, new PageRequest(0, 10));
MatcherAssert.assertThat(result.isFirstPage(), is(true));
User u = result.getContent().get(0);
Run Code Online (Sandbox Code Playgroud)
异常抛出:
org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [90016]; error code [90016]; could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract …Run Code Online (Sandbox Code Playgroud) 我正在构建一个使用Spring Data和Hibernate的简单Tomcat webapp.有一个终点可以完成很多工作,因此我想将工作卸载到后台线程,以便在完成工作时Web请求不会挂起10分钟以上.所以我在一个组件扫描包中写了一个新服务:
@Service
public class BackgroundJobService {
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public void startJob(Runnable runnable) {
threadPoolTaskExecutor.execute(runnable);
}
}
Run Code Online (Sandbox Code Playgroud)
然后ThreadPoolTaskExecutor在Spring中配置:
<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>
Run Code Online (Sandbox Code Playgroud)
这一切都很有效.但问题来自Hibernate.在我的runnable中,查询只有一半工作.我可以:
MyObject myObject = myObjectRepository.findOne()
myObject.setSomething("something");
myObjectRepository.save(myObject);
Run Code Online (Sandbox Code Playgroud)
但是如果我有延迟加载的字段,它会失败:
MyObject myObject = myObjectRepository.findOne()
List<Lazy> lazies = myObject.getLazies();
for(Lazy lazy : lazies) { // Exception
...
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.stackoverflow.MyObject.lazies, could not initialize proxy - …Run Code Online (Sandbox Code Playgroud) JpaSpecificationExecutor附带的方法是不够的,它们都没有给我我想要的东西:
Page<T> findAll(Specification<T> spec, Pageable pageable)
List<T> findAll(Specification<T> spec)
List<T> findAll(Specification<T> spec, Sort sort)
Run Code Online (Sandbox Code Playgroud)
第一种方法执行分页查询和计数查询.接下来的2个根本不执行分页.我需要的是以下之一:
Slice<T> findAll(Specification<T> spec, Pageable pageable)
List<T> findAll(Specification<T> spec, Pageable pageable)
Run Code Online (Sandbox Code Playgroud)
通过不扩展JpaSpecificationExecutor,我能够执行两个查询,但计数查询也是如此.在我的情况下,必须避免计数查询,因为它非常昂贵.问题是如何?
我在pom.xml中有一个带有Spring Data Elasticsearch插件的Spring Boot应用程序.我创建了一个文档类,我想索引:
@Document(indexName = "operations", type = "operation")
public class OperationDocument {
@Id
private Long id;
@Field(
type = FieldType.String,
index = FieldIndex.analyzed,
searchAnalyzer = "standard",
indexAnalyzer = "standard",
store = true
)
private String operationName;
@Field(
type = FieldType.Date,
index = FieldIndex.not_analyzed,
store = true,
format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm"
)
private Date dateUp;
@Field(
type = FieldType.String,
index = FieldIndex.not_analyzed,
store = false
)
private String someTransientData;
@Field(type = FieldType.Nested)
private List<Sector> sectors;
//Getter …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一种控制器方法,类似于支持QueryDsl的最新Gosling发布的Spring Data发布系列中记录的方法.我已经实现了控制器,如http://docs.spring.io/spring-data/jpa/docs/1.9.0.RELEASE/reference/html/#core.web.type-文档中的示例所示.安全.一切都在编译,当我启动应用程序时(使用Spring Boot 1.2.5.RELEASE),一切都很顺利.
但是,当我尝试调用我的rest端点时,我总是得到以下异常:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mysema.query.types.Predicate]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:101)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:80)
Run Code Online (Sandbox Code Playgroud)
我的猜测是,QuerydslPredicateArgumentResolver没有应用于请求,因此异常.但是QuerydslPredicateArgumentResolver当我查询Spring Boot管理端点时,我看到它被注册为bean /manage/beans.我也确保@EnableSpringDataWebSupport我的@Configuration班级没有效果.
我对控制器进行了注释@BasePathAwareController,因为我在Spring Data REST中使用它,我希望这些方法与Spring Data REST公开的方法类似.我也尝试过使用@RepositoryRestController,但这似乎并不重要.但是,当使用@RestController并将其放在与Spring Data REST正在使用的基本路径不同的路径下时,一切正常.所以问题是,它应该有效吗?
现在整个控制器是:
@RestController
@RequestMapping(value = "/query")
public class AvailController
{
private final AvailRepository repo;
@Autowired
public AvailController(AvailRepository repository)
{
this.repo = repository;
}
@RequestMapping(value = "/avails", method = GET)
public @ResponseBody …Run Code Online (Sandbox Code Playgroud) 我有一个简单的REST服务,可以使用Spring启动访问数据CrudRepository.
这个存储库已经实现了这样的分页和排序功能:
public interface FlightRepository extends CrudRepository<Flight, Long> {
List<Flight> findAll(Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)
打电话给:
Sort sort = new Sort(direction, ordering);
PageRequest page = new PageRequest(xoffset, xbase, sort);
return flightRepo.findAll(page);
Run Code Online (Sandbox Code Playgroud)
我想添加过滤到这个存储库(例如只返回实体id > 13 AND id < 27).CrudRepository似乎不支持此功能.有没有办法如何实现这一点,还是我需要使用不同的方法?
谢谢你的任何提示!
我无法弄清楚如何使用spring-data-mongodb从GridFS流式传输二进制文件,以及GridFSTemplate当我已经拥有权限时ObjectId.
GridFSTemplate返回GridFSResource(getResource())或GridFSFile(findX()).
我可以GridFSFile通过ID 获取:
// no way to get the InputStream?
GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)))
Run Code Online (Sandbox Code Playgroud)
但没有明显的路怎么走一个InputStream为GridFSFile.
只有GridFSResource让我获得corresonding的保持InputStream用InputStreamResource#getInputstream.但获得一个的唯一方法GridFSResource是通过它filename.
// no way to get GridFSResource by ID?
GridFSResource resource = gridFsTemplate.getResource("test.jpeg");
return resource.getInputStream();
Run Code Online (Sandbox Code Playgroud)
不知何故,GridFsTemplateAPI意味着文件名是唯一的 - 它们不是.该GridFsTemplate实现只返回的第一个元素.
现在我正在使用本机MongoDB API,一切都有意义:
GridFS gridFs = new GridFs(mongo);
GridFSDBFile nativeFile = gridFs.find(blobId);
return nativeFile.getInputStream();
Run Code Online (Sandbox Code Playgroud)
看起来我误解了Spring …
spring-data ×10
java ×6
spring ×5
querydsl ×2
hibernate ×1
jpa ×1
mongodb ×1
rest ×1
spring-boot ×1