标签: jpql

使用JPQL/HQL在JPA中对连接提取的集合进行排序

鉴于以下JPQL语句,我如何修改它,以便结果列表中的小猫按其age属性排序?

SELECT c FROM Cat c left join fetch c.kittens WHERE c.id = :id
Run Code Online (Sandbox Code Playgroud)

我尝试了多个approches,但没有任何运气.这基本上是我想要做的,但它不起作用:

SELECT c FROM Cat c left join fetch c.kittens k WHERE c.id = :id ORDER BY k.age
Run Code Online (Sandbox Code Playgroud)

java jpa hql jpql

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

JPQL ManyToMany选择

我在两个实体之间有一个多对多的关系:汽车和经销商.

在原生MySQL中我有:

car (id and other values)
dealership (id and other values)
car_dealership  (car_id and dealership_id)
Run Code Online (Sandbox Code Playgroud)

我想在JPQL中创建的查询是:

#Select List of cars in multiple dealerships
SELECT car_id FROM car_dealership WHERE dealership_id IN(1,2,3,56,78,999);
Run Code Online (Sandbox Code Playgroud)

使JPQL等效的正确方法是什么?

我的Java方法签名是:

public List<Car> findByDealership(List<Dealership> dealerships);
Run Code Online (Sandbox Code Playgroud)

我试过了

    //TOTALLY WRONG QUERY CALL!!!     
    Query query = em.createQuery("SELECT c FROM Car c WHERE :dealer_ids IN c.dealerships");
    List<Long> dealerIds = new ArrayList<Long>();
    for(Dealership d : dealerships) {
        dealerIds.add(d.getId());
    }
    query.setParameter(":dealer_ids", dealerIds); 
    List<Dealership> result = (List<Dealership>) query.getResultList();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这是我在java中的这种关系的JPA注释:

@Entity
@Table(name = …
Run Code Online (Sandbox Code Playgroud)

java database jpa jpql java-ee

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

QueryDSL/JPQL:如何构建连接查询?

我试过阅读QueryDSL文档,但我仍然很困惑.我习惯于编写很多SQL,但这是我第一次使用带有JPQL(JPA2)的QueryDSL.

我有以下实体:

@Entity
public class Provider implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;


    private String name;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "provider_contact", joinColumns = @JoinColumn(name = "contact_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "provider_id", referencedColumnName = "id"))
    @OrderColumn
    private Collection<Contact> contact;
}
Run Code Online (Sandbox Code Playgroud)

其中Contact是一个带有idpk 的简单实体.

@Entity
public class Contact {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    /**
     * User first name
     */
    @NotNull …
Run Code Online (Sandbox Code Playgroud)

jpa jpql querydsl

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

休眠时的ColumnTransformer

我有一个实体,我使用它ColumnTransformer来进行绑定和提取值:

@Entity
class BPoint {
    @Id
    private Integer id;

    @ColumnTransformer(read = "astext(shape)", write = "toshape(?)")
    private Shape shape;

}
Run Code Online (Sandbox Code Playgroud)

道:

class BPointDao {
    @Autowired
    private EntityManager em;

    @Override
    public Page<BPoint> findAll(Pageable pageable) {
        Query q = em.createQuery("from BPoint");
        List<BPoint> r = q.getResultList();
        int total = em.createQuery("select count(*)  from BPoint").getFirstResult();
        return new PageImpl(r, pageable, total);
    }
    @Override
    public Integer save(BPoint hbds) {
        em.persist(hbds);
        return hbds.getId();
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作,但是一旦我必须做一些需要使用sql函数的查询,我遇到一些问题,以这个有效的本机sql为例:

select * from BPoint h where inside(h.shape, 100) = 1;
Run Code Online (Sandbox Code Playgroud)

首先我尝试使用这样的hql: …

java orm hibernate jpa jpql

11
推荐指数
1
解决办法
3154
查看次数

具有多个SELECT NEW语句的jpa构造函数表达式

有没有办法SELECT NEWjpql查询中使用多个语句(Hibernate)?

这对我有用:

@Query("SELECT NEW com.test.project.dto.ItemService(g,s,l,r) "
        +" FROM Item g, Service s, Service l , Service r"
        +" WHERE s.id = g.id" 
        +" AND s.location = l.name"
        +" AND s.serviceType = 'type'"
        +" AND l.serviceType = 'Location'"
        +" AND l.area = r.name" 
        +" AND r.serviceType = 'Region'")
public List<Item> getAllItemsWithServices();
Run Code Online (Sandbox Code Playgroud)

我得到了预期的结果DTO.

@Component
public class ItemServiceDTO{

    private Item item;
    private Service serviceType;
    private Service serviceLocation;
    private Service serviceRegion;

    public ItemServiceDTO(item item, Service serviceType, Service …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate jpa jpql

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

如何使用弹簧数据jpa的投影和规格?

我无法一起使用Spring Data JPA投影和规范.我有以下设置:

实体:

@Entity
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "NAME", nullable = false)
    private String name;

    @Column(name = "CODE", nullable = false)
    private String code;

    ---getters & setters---

}
Run Code Online (Sandbox Code Playgroud)

投影界面:

public interface CountryProjection {
    String getName();
}
Run Code Online (Sandbox Code Playgroud)

国家规格:

public class CountrySpecification {
    public static Specification<Country> predicateName(final String name) {
        return new Specification<Country>() {
            @Override
            public Predicate toPredicate(Root<Country> eventRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(eventRoot.get(Country_.name), name);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

库: …

hibernate jpql spring-data-jpa spring-boot

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

Jpql从每个组中选择一个最大行

我对JPA比较陌生,我想独家使用jpql解决以下问题(注意我使用的实现是Datanucleus):我有一个版本化实体表,我想得到所有实体的最新版本在表中(即我有一个实体类,它有一个id(唯一标识一行,一个entityId(在整个版本中标识实体本身)和一个时间戳;我想得到所有entityId的最新版本实体).我目前的代码如下:

    String innerQueryString = "SELECT entity.entityId, max(entity.timestamp) " +
                  "FROM Entity entity" +
                  "GROUP BY entity.entityId";

    Query getQuery = getEntityManager().createQuery(innerQueryString);

    List<Object[]> queryRes = getQuery.getResultList();
    List<IEntity> ret = new ArrayList<IEntity>();

    for (Object[] res : queryRes) { 
        ret.add(getEntity((Long)res[0], (Date)res[1]));
    }

    return ret;
Run Code Online (Sandbox Code Playgroud)

其中getEntity获取指定entityId的实体数据,即时间戳.我已经找到了几个关于这段代码如何在sql中工作的资源http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in- sql /但我无法设法创建它的jpql版本.非常感谢帮助,谢谢.

java jpa jpql

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

今天的jpql日期比较

我需要一个jpql查询来查找所有LoadFileHistory,其中finishDate大于当前日期(从00:00:00开始).例如大于27/11/2012 00:00:00.

我已经有了这个"从LoadFileHistory o中选择o,其中o.finishDate = CURRENT_DATE",但没有得到任何东西.

java jpa jpql

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

在JPQL查询中使用数组

如何在JPQL查询中使用数组列表?我想要这样的事情:我正在传递这个

private static final String[] MASKS = {"30109", "30111"};
Run Code Online (Sandbox Code Playgroud)

public List<Account> findAccount(String[] Masks){
StringBuilder sb = new StringBuilder("from AccountTable a where SUBSTRING(a.Account,1,5) in :Masks ");
Query q = em.createQuery(sb.toString(), AccountTable.class)
                .setParameter("Masks",Masks);
}
Run Code Online (Sandbox Code Playgroud)

目前,错误是

Encountered array-valued parameter binding, but was expecting [java.lang.String (n/a)]; nested exception is java.lang.IllegalArgumentException: Encountered array-valued parameter binding, but was expecting [java.lang.String (n/a)]
Run Code Online (Sandbox Code Playgroud)

java hibernate jpa jpql

10
推荐指数
1
解决办法
6659
查看次数

java.time.Instant field cannot be filled by JPQL query using "current_timestamp" after update to SpringBoot 3 / Hibernate 6

I have a base class for persisted entities like this:

@EntityListeners(AuditListener.class)
@MappedSuperclass
public abstract class BaseEntity {
    @Id
    private String id;
    private Instant createdAt;
    private String createdBy;
    private Instant modifiedAt;
    private String modifiedBy;
    ...
Run Code Online (Sandbox Code Playgroud)

A listener to fill the created/modified fields on persiste/update:

public class AuditListener {
    @PrePersist
    private void onCreate(BaseEntity entity) {
        entity.setCreatedAt(Instant.now());
        entity.setCreatedBy(getIdUserLogged());
    }
    @PreUpdate
    private void onUpdate(BaseEntity entity) {
        entity.setModifiedAt(Instant.now());
        entity.setModifiedBy(getIdUserLogged());
    }
}
Run Code Online (Sandbox Code Playgroud)

For updates made by query the listener would now work and I've manually set …

hibernate jpql spring-boot sql-timestamp

10
推荐指数
1
解决办法
3391
查看次数