[英]Stored procedure not able to call from Hibernate
我正在尝试触发MySQL的存储过程,在MySQL中该存储过程运行良好,但是当我尝试从Hibernate触发时,它给出了异常。
org.hibernate.MappingException: Named query not known: GetEmployeeDetails
这是我的代码。
//Stored procedure
Query q = session.getNamedQuery("GetEmployeeDetails").setParameter("empId", 10);
List<?> result = q.list();
for(int i = 0; i < result.size(); i++) {
Employee e = (Employee)result.get(i);
System.out.println("Employee Name :"+e.getName());
}
我的员工班级是。
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Entity
public class Employee {
@Id
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我的存储过程
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetEmployeeDetails`(empid varchar(20))
BEGIN
select * from employee where id=empid;
END
您需要为Employee类定义命名查询。
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@NamedNativeQueries({
@NamedNativeQuery(
name = "GetEmployeeDetails",
query = "CALL GetEmployeeDetails(:empId)",
resultClass = Employee.class
)
})
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Entity
public class Employee {
@Id
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
您的代码似乎还可以,可能是mysql方面的其他一些错误,否则请使用其他替代方法来调用存储过程,如下所示。
Query query = session.createSQLQuery("CALL GetEmployeeDetails(:empId)").addEntity(Employee.class).setParameter("empId", 10);
详情请参见: http : //www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.