Hibernate(JPA) 多表查询结果为Object,转为自定义实体类

实体:product

@Entity

public class Product {

private String productNo;

private String name;

private String chandi;

private ProductType productType;

@Id

public String getProductNo() {

return productNo;

}

public void setProductNo(String productNo) {

this.productNo = productNo;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getChandi() {

return chandi;

}

public void setChandi(String chandi) {

this.chandi = chandi;

}

@ManyToOne(cascade ="CascadeType.All")

@JoinColumn(name="productType_id")

public ProductType getProductType() {

return productType;

}

public void setProductType(ProductType productType) {

this.productType = productType;

}

}

实体类ProductType

@Entity

public class ProductType {

private String typeNo;

private String Name;

private Set<Product> products;

@Id

public String getTypeNo() {

return typeNo;

}

public void setTypeNo(String typeNo) {

this.typeNo = typeNo;

}

public String getName() {

return Name;

}

public void setName(String name) {

Name = name;

}

@OneToMany(mappedBy="productType")

public Set<Product> getProducts() {

return products;

}

public void setProducts(Set<Product> products) {

this.products = products;

}

}

如果关联查询:createQuery("select p.chandit.name from Product p left join p.productType t group by p.productType ")会返回object类型要想对实体处理可以采取如下措施:

1、增加一个类(字段名为查询的字段名,要生成对应的geter seter方法,并且一定要有构造函数,且构造函数的参数是查询的字段)

public class ProductAndType {

private String name;

private String chandi;

public Product(String name, String chandi) {

this.name = name;

this.chandi = chandi;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getChandi() {

return chandi;

}

public void setChandi(String chandi) {

this.chandi = chandi;

}

}

2、修改查询语句createQuery("select new 包名.ProductAndType( p.chandi t.name )from Product p left join p.productType t group by p.productType ")这样即可转为ProductAndType类型,可对其操作。