[英]How to Map a CASE Statement alias to a java pojo attribute in JPA/JPQL?
JPQL: JPQL:
@Query(value="SELECT emp,CASE WHEN emp.country='india' THEN 'INDIAN' ELSE 'OTHER' END AS originCountry FROM EMPLOYEE emp") //originCountry is not a column of Entity/Table
List<Employee> findAllEmployee()
Now how to map originCountry to a java property/attribute?现在如何将 map originCountry 转换为 java 属性/属性? ALL result set attribute will be mapped to the employee object automatically but how to map the originCountry attribute as it is not coming from database table?
所有结果集属性将自动映射到员工 object 但是如何将 originCountry 属性映射到 map,因为它不是来自数据库表?
Java class: Java class:
@Table(name="employee")
@Entity
@Getter
@Setter
class Employee{
@Id
@Column(name="emp_id")
private String empId;
@Column(name="emp_name")
private String empName;
@Column(name="emp_address")
private String empAddress;
@Transient
private String originCountry; //I want to map CASE statement alias result to this variable
}
Actually @Airy's assumption is absolutely relevant!实际上@Airy 的假设是绝对相关的! I just have modeled the issue with a small
h2
-based project.我刚刚用一个基于
h2
的小型项目对问题进行了建模。 Disclaimer: it's just a piece of code of a synthetic model免责声明:这只是合成 model 的一段代码
Given : Pet
entity.给定:
Pet
实体。 It has a typeCode
property of Integer
.它的
typeCode
属性为Integer
。
Todo : Implement another property, that'll return pet's type name by its typeCode
. Todo :实现另一个属性,它将通过
typeCode
返回宠物的类型名称。
@Entity
public class Pet {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue
private Long id;
@Column
private String name;
@Column
private Integer typeCode;
@Formula("case type_code when 1 then 'Cat' when 2 then 'Dog' else 'Chupacabra' end")
private String typeName;
//get, set etc
@Override
public String toString() {
return new StringJoiner(", ", Pet.class.getSimpleName() + "[", "]")
.add("id=" + getId())
.add("name='" + getName() + "'")
.add("typeCode=" + getTypeCode())
.add("typeName='" + getTypeName() + "'")
.toString();
}
}
In a bootstrap:在引导程序中:
var cat = new Pet();
cat.setName("Oscar");
cat.setTypeCode(1);
var dog = new Pet();
dog.setName("Lucky");
dog.setTypeCode(2);
var customPet = new Pet();
customPet.setName("Smoking kills");
petRepository.saveAll(List.of(cat, dog, customPet));
And test:并测试:
public void interact() {
var pet1 = petRepository.findById(1L).get();
var pet2 = petRepository.findById(2L).get();
var pet = petRepository.findById(3L).get();
System.out.println(pet1);
System.out.println(pet2);
System.out.println(pet);
}
Console:
Pet[id=1, name='Oscar', age=6, typeCode=1, typeName='Cat', type=CAT]
Pet[id=2, name='Lucky', age=10, typeCode=2, typeName='Dog', type=DOG]
Pet[id=3, name='Smoking kills', age=null, typeCode=null, typeName='Chupacabra', type=null]
From Hibernate
's reference of formula :来自
Hibernate
的公式参考:
You can use a SQL fragment (aka formula) instead of mapping a property into a column
您可以使用 SQL 片段(又名公式)而不是将属性映射到列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.