标签: spring-data-jpa

JPQL中的LIMIT子句替代是什么?

我正在使用JPQL中的PostgreSQL查询实现.

这是一个原生的psql查询示例,工作正常,

SELECT * FROM students ORDER BY id DESC LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

JPQL中的相同查询不起作用,

@Query("SELECT s FROM Students s ORDER BY s.id DESC LIMIT 1")

Students getLastStudentDetails();
Run Code Online (Sandbox Code Playgroud)

似乎LIMIT子句在JPQL中不起作用.

根据我们可以使用的JPA文档setMaxResults/setFirstResult,任何人都可以告诉我如何在我的上述查询中使用它?

java mysql jpa jpql spring-data-jpa

36
推荐指数
5
解决办法
5万
查看次数

Spring Data JPA:Query如何返回非实体对象或对象列表?

我在我的项目中使用spring数据JPA.我正在玩数百万条记录.我有一个要求,我必须获取各种表的数据并构建一个对象,然后在UI上绘制它.现在如何实现我的Spring数据存储库.我已经读过它可以通过命名本机查询来实现.

如果命名的本机查询未返回实体或实体列表,则可以使用@SqlResultSetMapping批注将查询结果映射到正确的返回类型.

但是,当我尝试使用@SqlResultSetMapping它时,正在采取另一个entityResult.意思是我理解的是它只是将一些查询结果转换为实体结果集,但我想要一个非实体对象的结果集.

@SqlResultSetMapping(
    name="studentPercentile",
    entities={
        @EntityResult(
           entityClass=CustomStudent.class,
              fields={
                  @FieldResult(name="id", column="ID"),
                  @FieldResult(name="firstName", column="FIRST_NAME"),
                   @FieldResult(name="lastName", column="LAST_NAME")
              }         
        )
   }
) 
@NamedNativeQuery(
    name="findStudentPercentile", 
    query="SELECT * FROM STUDENT", 
    resultSetMapping="studentPercentile")
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我只是试图将学生实体的结果转化为另一个不是实体的pojo'CustomStudent '.(这个例子我试图只为POC目的执行,实际的用例很复杂,复杂的查询返回不同的结果集).

如何实现上述用例?除了使用名称查询之外还有其他方法我的存储库方法返回非实体对象吗?

java hibernate java-ee jpa-2.0 spring-data-jpa

33
推荐指数
3
解决办法
6万
查看次数

如何测试Spring对Spring Data存储库的声明性缓存支持?

我开发了一个MemberRepository扩展的Spring Data存储库接口org.springframework.data.jpa.repository.JpaRepository.MemberRepository有一个方法:

@Cacheable(CacheConfiguration.DATABASE_CACHE_NAME)
Member findByEmail(String email);
Run Code Online (Sandbox Code Playgroud)

结果由Spring缓存抽象缓存(由a支持ConcurrentMapCache).

我的问题是,我想要写一个集成测试(针对HSQLDB)断言结果被从数据库第一次检索,并从缓存中的第二次.

我最初想过嘲笑jpa基础设施(实体经理等),并以某种方式断言实体经理第二次没有被调用但看起来太难/笨重(参见/sf/answers/1640972021/).

那么有人可以提供有关如何测试带有注释的Spring Data Repository方法的缓存行为的建议@Cacheable吗?

testing spring spring-data spring-data-jpa spring-cache

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

Spring实体管理器和Spring Data Repository之间有什么区别?

我在网站上使用JPA.在探索了保存数据的选项后,我找到了2种方法.第一种方法是使用javax.persistence.EntityManager的实现.我使用LocalContainerEntityManagerFactoryBean来实例化EntityManager的实例.一旦我获得了EntityManager的实例,我就可以用它来保存实体.例如,

entityManager.merge(someEntity);
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用org.springframework.data.repository.CrudRepository的实例.一,我获得了一个CrudRepository的实例,我可以用它来保存一个实体.例如,

aCrudRepository.save(someEntity);
Run Code Online (Sandbox Code Playgroud)

使用EntityManager和CrudRepository将实体持久化到数据库之间有什么区别?这两种方法(实体管理器与crud存储库)有什么好处或坏处?

spring jpa spring-data spring-data-jpa

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

如何在Spring Boot中使用Spring管理的Hibernate拦截器?

是否有可能在Spring Boot中集成Spring管理的Hibernate拦截器(http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch14.html)?

我正在使用Spring Data JPA和Spring Data REST,并且需要一个Hibernate拦截器来对实体上的特定字段进行更新.

使用标准JPA事件,不可能获得旧值,因此我认为我需要使用Hibernate拦截器.

hibernate spring-data spring-data-jpa spring-data-rest spring-boot

32
推荐指数
6
解决办法
4万
查看次数

Spring Data Repository不会删除ManyToOne Entity

我目前正在尝试使用Spring Data存储库来删除我的一些实体.删除调用在没有任何异常/错误消息的情况下工作,但之后不会删除该实体.

这些是我的实体:

public class Board implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    private UUID uuid;

    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval = true, mappedBy = "board")
    private List<Post> posts = new ArrayList<Post>();
}
Run Code Online (Sandbox Code Playgroud)

public class Post implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne(optional = false)
    @JoinColumn(name="board_uuid", updatable = false, nullable = false)
    @JsonBackReference
    private Board board;
}
Run Code Online (Sandbox Code Playgroud)

存储库尽可能简单:

@Repository
public interface PostRepository extends CrudRepository<Post, Long> {
}
Run Code Online (Sandbox Code Playgroud)

删除调用类似于

postRepository.delete(50);
Run Code Online (Sandbox Code Playgroud)

有什么想法为什么这种变化没有反映在数据库中? …

java spring hibernate spring-data-jpa

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

Spring Data JPA智能无法在Intellij中运行

我已经使用Spring Data JPA设置了一个spring boot项目,但我没有看到Spring数据jpa的智能. 在此输入图像描述

屏幕截图显示问题,我的餐厅实体有一个变量调用restaurantAddress,我试图让intelliJ帮助我完成编码,但没有智能显示.

我的项目设置如下:

申请类:

@SpringBootApplication
@ComponentScan(basePackages = {"com.mycompany"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>food</artifactId>
    <version>1.0-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.7.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Dependencies for RESTful Web Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Dependencies for JPA Data Persistence -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--JDBC-->
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

    </dependencies>


    <build>
        <finalName>food</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration> …
Run Code Online (Sandbox Code Playgroud)

spring intellij-idea spring-data spring-data-jpa

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

Spring-Data JPA:保存引用现有实体的新实体

问题基本上与下面的问题相同:

JPA级联持久化并且对分离实体的引用会抛出PersistentObjectException.为什么?

我正在创建一个引用现有的独立实体的新实体.现在,当我在Spring数据存储库中保存此实体时,会抛出异常:

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist
Run Code Online (Sandbox Code Playgroud)

如果我们看一下spring数据JPA的源代码中的save()方法,我们看到:

public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我们看看isNew()in AbstractEntityInformation

public boolean isNew(T entity) {

    return getId(entity) == null;
}
Run Code Online (Sandbox Code Playgroud)

所以基本上如果我保存()一个新实体(id == null),spring数据将始终调用persist,因此这种情况总是会失败.

在向集合添加新项目时,这似乎是一个非常典型的用例.

我该如何解决这个问题?

编辑1:

注意:

此问题与如何保存引用Spring JPA中现有实体的新实体没有直接关系.详细说明假设您获得了通过http创建新实体的请求.然后,您从请求中提取信息,并创建您的实体和现有的实体.因此,他们将永远脱离.

java merge persist spring-data spring-data-jpa

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

Spring Boot应用程序启动速度非常慢

我有一个简单的Spring Boot应用程序,它连接到PostgreSQL数据库并充当JSON服务.不知怎的,创业公司变得非常慢,见时间10:37:10和10:38:00:

2015-05-09 10:37:09.649  INFO 20880 --- [lication.main()] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-05-09 10:37:09.651  INFO 20880 --- [lication.main()] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.20
2015-05-09 10:37:09.767  INFO 20880 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-05-09 10:37:09.767  INFO 20880 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2970 ms
2015-05-09 10:37:09.979  INFO 20880 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2015-05-09 10:37:09.985  INFO 20880 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-05-09 …
Run Code Online (Sandbox Code Playgroud)

postgresql spring spring-data spring-data-jpa spring-boot

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

如何使用JpaRepository进行批量(多行)插入?

当从服务层调用long 的saveAll方法时,Hibernate的跟踪日志记录显示每个实体发出的单个SQL语句.JpaRepositoryList<Entity>

我可以强制它进行批量插入(即多行)而无需手动操作EntityManger,事务等甚至原始SQL语句字符串?

对于多行插入,我的意思不仅仅是从:

start transaction
INSERT INTO table VALUES (1, 2)
end transaction
start transaction
INSERT INTO table VALUES (3, 4)
end transaction
start transaction
INSERT INTO table VALUES (5, 6)
end transaction
Run Code Online (Sandbox Code Playgroud)

至:

start transaction
INSERT INTO table VALUES (1, 2)
INSERT INTO table VALUES (3, 4)
INSERT INTO table VALUES (5, 6)
end transaction
Run Code Online (Sandbox Code Playgroud)

而是:

start transaction
INSERT INTO table VALUES (1, 2), (3, 4), (5, 6)
end transaction
Run Code Online (Sandbox Code Playgroud)

在PROD中,我使用的是CockroachDB,性能差异很大.

下面是一个重现问题的简单示例(H2为简单起见). …

hibernate spring-data-jpa kotlin spring-boot cockroachdb

31
推荐指数
3
解决办法
4万
查看次数