[英]Stored procedure not able to call from Hibernate
I'm trying to trigger a stored procedure of MySQL, in MySQL the stored procedure is working fine, but when I try to trigger from Hibernate, its giving exception. 我正在尝试触发MySQL的存储过程,在MySQL中该存储过程运行良好,但是当我尝试从Hibernate触发时,它给出了异常。
org.hibernate.MappingException: Named query not known: GetEmployeeDetails
Here is my code. 这是我的代码。
//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());
}
My Employee class is. 我的员工班级是。
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;
}
}
My Stored procedure 我的存储过程
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetEmployeeDetails`(empid varchar(20))
BEGIN
select * from employee where id=empid;
END
You need to define named query for your Employee class. 您需要为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;
}
}
Your code seems to be ok.May be it will be of some other mistakes in mysql side.Else use other alternatives to call the stored procedure like below. 您的代码似乎还可以,可能是mysql方面的其他一些错误,否则请使用其他替代方法来调用存储过程,如下所示。
Query query = session.createSQLQuery("CALL GetEmployeeDetails(:empId)").addEntity(Employee.class).setParameter("empId", 10);
See more at: http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/ 详情请参见: http : //www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.