我有一个服务类,它通过使用 调用 JPA 存储库来接收汽车列表carRepository.retrieveCars()。存储库方法使用本机查询来检索记录。
public interface CarRepository extends JpaRepository<Car, String> {
@Query(nativeQuery = true,
value = "select *" +
"from car_records")
}
List<Car> retrieveCars();
Run Code Online (Sandbox Code Playgroud)
现在我想传递参数carRepository.retrieveCars(Long vinNo, Long serialNo)并在查询中使用它们。我想我需要一些东西作为准备好的陈述。但是我不确定如何实现。
public interface CarRepository extends JpaRepository<TRace, String> {
@Query(nativeQuery = true,
value = "select *" +
"from car_records" +
"where carVinNo = ?! and carSerialNo >= ?1")
}
query.setParameter(1, vinNo, 2,serialNo); //this is certainly not correct implementation
List<Car> retrieveCars(vinNo, serialNo);
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用HQL使用JOIN FETCH获取我的实体以及子实体,如果我想要所有结果,这是正常工作但如果我想要一个页面则不是这样
我的实体是
@Entity
@Data
public class VisitEntity {
@Id
@Audited
private long id;
.
.
.
@OneToMany(cascade = CascadeType.ALL,)
private List<VisitCommentEntity> comments;
}
Run Code Online (Sandbox Code Playgroud)
因为我有数百万次访问,我需要使用Pageable,我想在单个数据库查询中获取注释,如:
@Query("SELECT v FROM VisitEntity v LEFT JOIN FETCH v.comments WHERE v.venue.id = :venueId and ..." )
public Page<VisitEntity> getVenueVisits(@Param("venueId") long venueId,...,
Pageable pageable);
Run Code Online (Sandbox Code Playgroud)
该HQL调用抛出以下异常:
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=com.ro.lib.visit.entity.VisitEntity.comments,tableName=visitdb.visit_comment,tableAlias=comments1_,origin=visitdb.visit visitentit0_,columns={visitentit0_.visit_id ,className=com.ro.lib.visit.entity.VisitCommentEntity}}] …Run Code Online (Sandbox Code Playgroud) 我有一个简单的存储过程,我用它来测试Spring Data JPA存储过程功能.
create or replace procedure plus1inout (arg in int,res1 out int,res2 out int) is
BEGIN
res1 := arg + 1;
res2 := res1 + 1;
END;
Run Code Online (Sandbox Code Playgroud)
我的代码是:
@Repository
public interface AdjudConverDateSPRepository extends JpaRepository<AdjudConverDateSP, Long> {
@Procedure(name = "plus1")
Object[] plus1(@Param("arg") Integer arg);
}
@Entity
@NamedStoredProcedureQuery(name = "plus1", procedureName = "ADJUD.PLUS1INOUT",
parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, name = "arg", type = Integer.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "res1", type = Integer.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "res2", type …Run Code Online (Sandbox Code Playgroud) java stored-procedures hibernate spring-data spring-data-jpa
我有一个非常复杂的模型.实体有很多关系,等等.
我尝试使用Spring Data JPA并准备了一个存储库.
但是当我调用metod findAll()时,对象a的规范有一个性能问题,因为对象非常大.我知道,因为当我调用这样的方法时:
@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();
Run Code Online (Sandbox Code Playgroud)
我的表现没有任何问题.
但是当我调用时
List<Customer> findAll();
Run Code Online (Sandbox Code Playgroud)
我的表现存在很大问题.
问题是我需要使用Specifications for Customer调用findAll方法,这就是为什么我不能使用返回对象数组列表的方法.
如何编写方法来查找具有Customer实体规范但仅返回ID的所有客户.
像这样:
List<Long> findAll(Specification<Customer> spec);
Run Code Online (Sandbox Code Playgroud)
请帮忙.
使用Spring Data REST,如果您有一个OneToMany或一个ManyToOne关系,PUT操作会在"非拥有"实体上返回200,但实际上并不会保留已连接的资源.
示例实体:
@Entity(name = 'author')
@ToString
class AuthorEntity implements Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id
String fullName
@ManyToMany(mappedBy = 'authors')
Set<BookEntity> books
}
@Entity(name = 'book')
@EqualsAndHashCode
class BookEntity implements Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id
@Column(nullable = false)
String title
@Column(nullable = false)
String isbn
@Column(nullable = false)
String publisher
@ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL])
Set<AuthorEntity> authors
}
Run Code Online (Sandbox Code Playgroud)
如果您使用a来支持它们PagingAndSortingRepository,您可以获取a Book,按照authors书上的链接进行PUT,并使用要关联的作者的URI.你不能走另一条路.
如果您对作者执行GET并在其books链接上执行PUT …
java spring-data spring-data-jpa spring-data-rest spring-boot
我正在使用Spring Data JPA,我有一个PagingAndSortingRepository<Contact, Long>使用JPASpecificationExecutor<Contact>.我将一个Specification和一个Pageable实例传递给.findAll()此存储库的方法以获取Page<Contact>.
但是,我的Contact实体有很多额外的字段和映射,我不需要在前端.所以,我有一个ContactDto只包含必要的字段,我也可以从一个转换方法Contact来ContactDto.
private ContactDto convertToContactDto(Contact contact) {
//do the conversion
}
Run Code Online (Sandbox Code Playgroud)
我将如何使用此转换方法将其转换Page<Contact>为Page<ContactDto>?
我可以得到它的内容Page<Contact>并像这样进行转换.
final Page<Contact> contactPage = pagingAndSortingContactRepository
.findAll(ContactSpecification.findByFirstNmLike(firstNm), pageable);
final Collection<ContactDto> contactDtos = contactPage.getContent()
.stream()
.map(this::convertToContactDto)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
但后来我留下了一个Collection而不是一个Page,我不知道如何把它Collection变成了内容Page.有没有办法做到这一点?或者是否有另一种方法来调用Page<Contact>实例本身的转换?
我目前正在构建一个REST API,我希望客户端可以轻松地过滤特定实体的大多数属性.使用QueryDSL与结合春季数据REST(由奥利弗·基尔克一个例子),让我很容易地通过允许客户通过组合是指性质(如查询参数进行过滤得到我想要的东西90% /users?firstName=Dennis&lastName=Laumen).
我甚至可以通过实现QuerydslBinderCustomizer接口来自定义查询参数和实体属性之间的映射(例如,用于不区分大小写的搜索或部分字符串匹配).这一切都很棒,但我也希望客户能够使用范围过滤某些类型.例如关于像出生日期这样的财产,我想做类似下面的事情,/users?dateOfBirthFrom=1981-1-1&dateOfBirthTo=1981-12-31.基于数字的属性也是如此/users?idFrom=100&idTo=200.我觉得这应该可以使用QuerydslBinderCustomizer界面,但这两个库之间的集成没有得到非常广泛的记录.
总结一下,这可能使用Spring Data REST和QueryDSL吗?如果是这样,怎么样?
spring querydsl spring-data spring-data-jpa spring-data-rest
我正在尝试迁移该应用程序.我正在从Hibernate工作到Spring Data Jpa.
虽然spring数据jpa提供了简单的查询构建方法,但我仍然坚持创建使用And和的查询方法Or operator.
MethodName - findByPlan_PlanTypeInAndSetupStepIsNullOrStepupStepIs(...)
当它转换为查询时,前两个表达式被组合并执行为[(exp1 and exp2) or (exp3)].
而要求是](exp1) and (exp2 or exp3)].
任何人都可以告诉我,如果这是可以实现的 Spring data jpa?
我有Java 8 Spring网络应用程序,它将支持多个区域.我需要为客户位置制作日历活动.因此,假设我的网站和Postgres服务器托管在MST时区(但我想如果我们去云端,它可能就在任何地方).但客户是在美国东部时间.所以,按照我读到的一些最佳实践,我想我会以UTC格式存储所有日期时间.数据库中的所有日期时间字段都声明为TIMESTAMP.
所以这是我如何采用LocalDateTime并转换为UTC:
ZonedDateTime startZonedDT = ZonedDateTime.ofLocal(dto.getStartDateTime(), ZoneOffset.UTC, null);
//appointment startDateTime is a LocalDateTime
appointment.setStartDateTime( startZonedDT.toLocalDateTime() );
Run Code Online (Sandbox Code Playgroud)
现在,例如,当搜索日期时,我必须从请求的日期时间转换为UTC,获取结果并转换为用户时区(存储在数据库中):
ZoneId userTimeZone = ZoneId.of(timeZone.getID());
ZonedDateTime startZonedDT = ZonedDateTime.ofLocal(appointment.getStartDateTime(), userTimeZone, null);
dto.setStartDateTime( startZonedDT.toLocalDateTime() );
Run Code Online (Sandbox Code Playgroud)
现在,我不确定这是正确的方法.我也想知道如果因为我从LocalDateTime到ZonedDateTime,反之亦然,我可能会失去任何时区信息.
这是我所看到的,这对我来说似乎不正确.当我从UI收到LocalDateTime时,我得到了这个:
2016-04-04T08:00
Run Code Online (Sandbox Code Playgroud)
ZonedDateTime =
dateTime=2016-04-04T08:00
offset="Z"
zone="Z"
Run Code Online (Sandbox Code Playgroud)
然后,当我将转换后的值分配给我的约会LocalDateTime时,我存储:
2016-04-04T08:00
Run Code Online (Sandbox Code Playgroud)
我觉得因为我存储在LocalDateTime中我失去了转换为ZonedDateTime的时区.
我应该让我的实体(约会)使用ZonedDateTime而不是LocalDateTime,以便Postgres不会丢失该信息吗?
---------------- 编辑 ----------------
在Basils出色的答案之后,我意识到我很不喜欢用户时区 - 所有约会都是针对特定位置的,因此我可以将所有日期时间存储为UTC,然后在检索时将它们转换为位置时区.我提出了以下后续问题
我有一个模型有一个相当大的子实体图和hibernate最终制作了大约9个语句懒洋洋地获取所需的所有数据但大约4级深度我得到一个"无法初始化代理 - 没有会话"错误,我是不知道为什么.
调节器
@Transactional(readOnly = true)
@RequestMapping(value = "/v2/plans", method = RequestMethod.GET)
public @ResponseBody List<PlanPresenter> show(HttpServletRequest request) throws Exception {
List<PlanPresenter> planPresenters = new ArrayList<>();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Plan> planQuery = criteriaBuilder.createQuery(Plan.class);
Root<Plan> root = planQuery.from(Plan.class);
if (request.getParameter("region") != null || request.getParameter("group") != null) {
List<Predicate> criteria = new ArrayList<Predicate>();
if (request.getParameter("region") != null) {
criteria.add(criteriaBuilder.equal(root.get(Plan_.region), request.getParameter("region")));
}
if (request.getParameter("group") != null) {
criteria.add(criteriaBuilder.equal(root.get(Plan_.groupCode), request.getParameter("group")));
criteria.add(root.get(Plan_.planSetId).in(groupPlanSetIds));
} else {
criteria.add(root.get(Plan_.planSetId).in(currentPlanSetIds));
}
Query query = entityManager.createQuery(planQuery.where(criteriaBuilder.and(criteria.toArray(new Predicate[]{}))));
for (Plan …Run Code Online (Sandbox Code Playgroud) spring-data-jpa ×10
java ×8
spring ×5
spring-data ×5
hibernate ×3
jpa ×2
spring-boot ×2
c3p0 ×1
criteria-api ×1
java-time ×1
querydsl ×1
sql ×1