标签: spring-data

规范中的spring-data子查询

Spring数据,Oliver Gierke的优秀库,有一个叫做规范(org.springframework.data.jpa.domain.Specification)的东西.有了它,您可以生成多个谓词来缩小搜索条件.

有人可以提供在规范中使用子查询的示例吗?

我有一个对象图,搜索条件可能非常多毛.我想使用规范来帮助缩小搜索范围,但我需要使用子查询来查看对象图中的某些子元素(在集合中)是否满足我的搜索需求.

提前致谢.

spring subquery criteria-api spring-data

16
推荐指数
1
解决办法
2万
查看次数

计入Spring Data MongoDB存储库

我想知道是否有任何机制可以count在带有@Query注释的Spring Data MongoDB存储库中使用?我很乐意收到我所拥有的文件数量,而无需获得所有这些文件.

基本上,相当于Java中的这个:

db.test.find({"type":"foo"}).count 
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data

16
推荐指数
2
解决办法
2万
查看次数

可以通过Repository访问Spring Data + MongoDB GridFS吗?

我最近发现了GridFS,我想将其用于带元数据的文件存储.我只是想知道是否可以使用a MongoRepository来查询GridFS?如果是的话,有人可以举个例子吗?

如果有的话,我也会使用Hibernate来解决问题.

原因是:我的元数据包含许多不同的字段,查询存储库比new Query(Criteria.where(...))为每个方案编写一些更容易.我希望也可以简单地使用Java对象并通过REST API提供它而不需要文件本身.

编辑:我正在使用

  • Spring 4 Beta
  • Spring Data Mongo 1.3.1
  • Hibernate 4.3 Beta

spring mongodb gridfs spring-data spring-data-mongodb

16
推荐指数
1
解决办法
9167
查看次数

在JUnit测试用例上获取LazyInitializationException

在Spring MVC应用程序中运行JUnit Test时出现问题.测试1(insertTweet)似乎运行正常,但是在测试2中我得到一个"LazyInitializationException"异常(参见下面的完整stactrace).我明白为什么它被抛出但不确定为什么会话正在关闭以及如何在每次测试2开始时重新打开它(或保持现有会话打开以完成剩余的测试)?我已经粘贴了与Test Classes一起抛出的整个StackTrace.

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.project.user.User.tweets, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
    at org.hibernate.collection.internal.AbstractPersistentCollection.write(AbstractPersistentCollection.java:370)
    at org.hibernate.collection.internal.PersistentBag.add(PersistentBag.java:291)
    at com.project.core.tweet.Tweet.<init>(Tweet.java:113)
    at com.project.core.service.impl.FanoutServiceTester.insertTweet(FanoutServiceTester.java:69)
    at com.project.core.service.impl.FanoutServiceTester.testInsertRetweet(FanoutServiceTester.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) …
Run Code Online (Sandbox Code Playgroud)

junit spring hibernate jpa-2.0 spring-data

16
推荐指数
4
解决办法
2万
查看次数

Java SE + Spring Data + Hibernate

我正在尝试使用Spring Data + Hibernate启动Java SE应用程序,并且到目前为止完成了以下操作:

配置文件

@Configuration
@PropertySource("classpath:hibernate.properties")
@EnableJpaRepositories
@EnableTransactionManagement
public class JpaConfiguration {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN =
            "entitymanager.packages.to.scan";

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(
                env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL)); …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-data

16
推荐指数
2
解决办法
2万
查看次数

SpringData JPA Repository方法查询有哪些?

在Spring-data JPA中,无论如何都要创建一个方法查询,实际上是通过像?

我有以下方法查询

public MakeModel findByModelIgnoreCase(String model);
Run Code Online (Sandbox Code Playgroud)

我真正想要的是一个表达方式.我是否需要创建Criteria或@Query注释?我问得太多了吗?

   //Stupid example of what I want to be able to do

    public MakeModel findByFuzzyModelIgnoreCase(String model);
Run Code Online (Sandbox Code Playgroud)

真的,我猜它的核心,我想做一个表搜索.我在Spring Data下面使用了Hibernate,所以我想我可以使用像Hibernate Search这样的搜索api.我愿意接受这里的建议.

spring hibernate jpa spring-data

16
推荐指数
2
解决办法
1万
查看次数

Spring Data Rest:未调用RepositoryEventHandler方法

我正在尝试将Spring Data REST文档中描述的RepositoryEventHandler添加到下面显示的REST存储库:

@RepositoryRestResource(collectionResourceRel = "agents", path = "/agents")
public interface AgentRepository extends CrudRepository<Agent, Long> {
    // no implementation required; Spring Data will create a concrete Repository
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个AgentEventHandler:

@Component
@RepositoryEventHandler(Agent.class)
public class AgentEventHandler {

    /**
     * Called before {@link Agent} is persisted 
     * 
     * @param agent
     */
    @HandleBeforeSave
    public void handleBeforeSave(Agent agent) {

        System.out.println("Saving Agent " + agent.toString());

    }
}
Run Code Online (Sandbox Code Playgroud)

并在@Configuration组件中声明它:

@Configuration
public class RepositoryConfiguration {

    /**
     * Declare an instance of the {@link AgentEventHandler}
     *
     * …
Run Code Online (Sandbox Code Playgroud)

java spring spring-data spring-data-rest

16
推荐指数
1
解决办法
9063
查看次数

(可选)在Spring Data Rest中禁用HATEOAS格式

所以假设我有一个现有的应用程序有两个端点/人和/裤子.呼叫GET /人员返回:

[
    {
        "name":"john",
        "age":37,
        "pants":[
            {
                "color":"green",
                "brand":"levis",
                "size":"medium"
            },
            {
                "color":"indigo",
                "brand":"jncos",
                "size":"medium-with-huge-legs"
            }
        ]
    },
    {
        "name":"june",
        "age":23,
        "pants":[
            {
                "color":"pink",
                "brand":"gap",
                "size":"small"
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

如果我使用Spring Data Rest并拨打GET/person,我会收到类似的信息:

{
    "_links":{
        "next":{
            "href":"http://myapp.com/people?page=1&size=20"
        },
        "self":{
            "href":"http://myapp.com/people{&page,size,sort}",
            "templated":true
        },
        "search":{
            "href":"http://myapp.com/people/search"
        }
    },
    "_embedded":{
        "people":[
            {
                "name":"john",
                "age":37,
                "_links":{
                    "self":{
                        "href":"http://myapp.com/people/john"
                    },
                    "pants":{
                        "href":"http://myapp.com/people/john/pants"
                    }
                }
            },
            {
                "name":"june",
                "age":23,
                "_links":{
                    "self":{
                        "href":"http://myapp.com/people/june"
                    },
                    "pants":{
                        "href":"http://myapp.com/people/june/pants"
                    }
                }
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

假设我有一堆我不想改变的现有客户端 - 在某些情况下是否有任何方法可以禁用响应的超媒体部分(比如Accept ="application/json")但是为了启用它们其他人(Accept …

rest hateoas spring-data hypermedia spring-data-rest

16
推荐指数
1
解决办法
1万
查看次数

Spring JPA Repository动态查询

目前我一直在使用以下Spring JPA Repository基础自定义查询,它工作正常,

 @Query("SELECT usr FROM User usr  WHERE usr.configurable = TRUE "
              + "AND (" +
                        "lower(usr.name) like lower(:filterText) OR lower(usr.userType.classType.displayName) like lower(:filterText) OR lower(usr.userType.model) like lower(:filterText)"
              +      ")"
              + "")
  public List<User> findByFilterText(@Param("filterText") String filterText, Sort sort);
Run Code Online (Sandbox Code Playgroud)

当过滤器文本将成为逗号分隔值时,我需要修改此查询.但是按照以下方式,它将是一个动态查询,我该如何执行它.

我需要构建动态查询,

String sql = "SELECT usr FROM User usr WHERE usr.configurable = TRUE";

for(String word : filterText.split(",")) {
                sql += " AND (lower(usr.name) like lower(:" + word + ") OR lower(usr.userType.classType.displayName) like lower(:" + word + ") OR lower(usr.userType.model) like …
Run Code Online (Sandbox Code Playgroud)

java spring jpa spring-data spring-data-jpa

16
推荐指数
2
解决办法
4万
查看次数

使用Spring DATA JPA创建自定义查询?

我正在使用Spring Data JPA开展项目.我在数据库中有一个表作为my_query.

我想创建一个方法,该方法将字符串作为参数,然后在数据库中将其作为查询执行.

方法:

executeMyQuery(queryString)
Run Code Online (Sandbox Code Playgroud)

例如,当我通过

queryString= "SELECT * FROM my_query"
Run Code Online (Sandbox Code Playgroud)

那么它应该在DB级别运行该查询.

存储库类如下.

public interface MyQueryRepository extends JpaRepository<MyQuery, Long>{
    public MyQuery findById(long id);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "?1", nativeQuery = true)
    public void executeMyQuery(String query);

}
Run Code Online (Sandbox Code Playgroud)

但是,它没有像我预期的那样工作.它给出以下错误.

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''select * from my_query;'' at line 1
Run Code Online (Sandbox Code Playgroud)

还有其他办法,我可以实现这个目标.提前致谢

mysql sql spring spring-data spring-data-jpa

16
推荐指数
1
解决办法
6万
查看次数