1. 程式人生 > >hibernate命名查詢

hibernate命名查詢

JavaBean如下:

   @Entity
@Table(name="t_customer")
@SqlResultSetMapping(name="res",entities={@EntityResult(entityClass=Customer.class,fields={
@FieldResult(name="cid",column="cid"),@FieldResult(name="name",column="name")})})

@NamedNativeQuery(name="ssql",query="select * from t_customer",resultSetMapping="res"

)
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer cid;
@Type(type="string")
private String name;

@OneToMany(targetEntity=Order.class, mappedBy="customer")
private Set<Order> orders = new HashSet<>();


public Integer getCid() {
return cid;
}


public void setCid(Integer cid) {
this.cid = cid;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public Set<Order> getOrders() {
return orders;
}


public void setOrders(Set<Order> orders) {
this.orders = orders;
}


@Override
public String toString() {
return "Customer [cid=" + cid + ", name=" + name + "]";
}

測試程式碼如下:
@Test
public void test2(){
Session session  = HibernateUtils.openSession();
session.beginTransaction();

Query query = session.getNamedQuery("ssql");
System.out.println(query.list());

session.getTransaction().commit();
session.close();

}

結果:[Customer [cid=1, name=張三], Customer [cid=2, name=張一一], Customer [cid=3, name=張三丰]]

紅色程式碼一定要配置,否則產生異常

出現問題的原因:hibernate不知道執行select * from t_customer後如果將結果封裝。



}