存储过程无法从Hibernate调用

时间:2016-03-22 03:52:58

标签: java mysql hibernate stored-procedures

我正在尝试触发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

2 个答案:

答案 0 :(得分:1)

您需要为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;
    }
}

答案 1 :(得分:1)

您的代码似乎没问题。可能是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/