使用jpa进行两表联查时总会有字段名相同,所以需要用别名进行区分;
例子:
department表同时包含子级id和父级id:
查询语句为:
select d.id,d.name,d.description,d.parent_id,temp.name as parent_name
from department d,department temp
where d.parent_id=?1 and if(d.parent_id=-1,d.id=temp.id,d.parent_id=temp.id)
此时希望同时获取部门信息、部门的父级id和父级部门名称,但不希望在department表在新建一列parent_name,所以我们可以使用@Transient注解表示该属性并非是一个要映射到数据库表中的字段;
但使用@Transient注解需要注意:
1、直接将@Transient注解直接加在parentName属性上,数据库不会创建parent_name字段,上述查询也无法获取值;
2、将@Transient注解加在parentName属性的get方法上,数据库会创建parent_name字段,上述查询可以获取值;
3、将@Transient注解加在parentName属性的set方法上,数据库不会创建parent_name字段,上述查询可以获取值;
关键代码如下:
package cn.test.bean;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* 部门实体类
*
*/
@Entity
@Table(name="department")
public class Department {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private Long parentId;
private String description;
private String parentName;
@Transient
private List<Department> childrens;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParentName() {
return parentName;
}
@Transient
public void setParentName(String parentName) {
this.parentName = parentName;
}
public List<Department> getChildrens() {
return childrens;
}
public void setChildrens(List<Department> childrens) {
this.childrens = childrens;
}
}
package cn.test.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import cn.test.bean.Department;
public interface DepartmentRepository extends JpaRepository<Department, Long>{
@Query(value="select d.id,d.name,d.description,d.parent_id,temp.name as parent_name " +
"from department d,department temp " +
"where d.parent_id=?1 and if(d.parent_id=-1,d.id=temp.id,d.parent_id=temp.id)",nativeQuery=true)
public List<Department> testAs(Long parentId);
}