Tag Archives: hibernate

How to call stored procedure in Hibernate

http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
In this tutorial, you will learn how to call a store procedure in Hibernate.
MySQL store procedure
Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data.

SQL

DELIMITER $$

CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20))
BEGIN
   SELECT * FROM stock where stock_code = int_stockcode;
   END $$

DELIMITER ;

In MySQL, you can simple call it with a call keyword :

SQL

CALL GetStocks('7277');

Hibernate call store procedure
In Hibernate, there are three approaches to call a database store procedure.
1. Native SQL – createSQLQuery
You can use createSQLQuery() to call a store procedure directly.

Java

Query query = session.createSQLQuery(
	"CALL GetStocks(:stockCode)")
	.addEntity(Stock.class)
	.setParameter("stockCode", "7277");
			
List result = query.list();
for(int i=0; i<result.size(); i++){
	Stock stock = (Stock)result.get(i);
	System.out.println(stock.getStockCode());
}

2. NamedNativeQuery in annotation
Declare your store procedure inside the @NamedNativeQueries annotation.

Java

//Stock.java
...
@NamedNativeQueries({
	@NamedNativeQuery(
	name = "callStockStoreProcedure",
	query = "CALL GetStocks(:stockCode)",
	resultClass = Stock.class
	)
})
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable {
...

Call it with getNamedQuery().

Java

Query query = session.getNamedQuery("callStockStoreProcedure")
	.setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
	Stock stock = (Stock)result.get(i);
	System.out.println(stock.getStockCode());
}

3. sql-query in XML mapping file
Declare your store procedure inside the “sql-query” tag.

Markup

<!-- Stock.hbm.xml -->
...
<hibernate-mapping>
    <class name="com.mkyong.common.Stock" table="stock" ...>
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
        </property>
        ...
    </class>
    
    <sql-query name="callStockStoreProcedure">
	<return alias="stock" class="com.mkyong.common.Stock"/>
	<![CDATA[CALL GetStocks(:stockCode)]]>
    </sql-query>
	
</hibernate-mapping>

Call it with getNamedQuery().

Java

Query query = session.getNamedQuery("callStockStoreProcedure")
	.setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
	Stock stock = (Stock)result.get(i);
	System.out.println(stock.getStockCode());
}

Conclusion
The above three approaches are doing the same thing, call a store procedure in database. There are not much big different between the three approaches, which method you choose is depend on your personal prefer.

com.microsoft.sqlserver . jdbc.SQLServerException : invalid object name ‘XX’

Myeclipse error message:
Error: com. Microsoft. Essentially. JDBC. SQLServerException: object name ‘xx’ is invalid
Warning: SQL Error: 208, SQLState: S0002
 
Error behavior: HQL statements can run in sqlserver, but run in hibernate to report an error.
Solution: The Settings in the.hbm.xml file of the data table mapping are incorrect. The database name catalog=”eportal” should be added, and the schema name schema=” DBO “should also be added.
This is a new feature in sqlserver2005, in mysql can be omitted.

SQL error: 156, sqlstate: S1000 error encountered in Hibernate

I encountered such a mistake today
Util. SQL Error JDBCExceptionReporter 77) : 156. SQLState: S1000
(util. JDBCExceptionReporter 78) near the keyword ‘plan for grammar mistakes.
.
Caused by: java.sql.sqlexception: syntax error near keyword ‘plan’.
…….
The web search explanation is caused by some values that have the same name as the key field in SQL2005.
Solution: Just change the plan name to something else, such as EMPPLAN

SQL Error: 904, SQLState: 42000

Question:

WARN 2011-03-04 09:33:18 org.hibernate.util.JDBCExceptionReporter – SQL Error: 904, SQLState: 42000

the ERROR 2011-03-04 09:33:18 org. Hibernate. Util. JDBCExceptionReporter – ORA – 00904: “MENU0_”. “MENU_OPEN_IN_HOME” : identifier is invalid

Hibernate: select portletloc0_.PORTLET_LOCATION_ROW as col_0_0_, portletloc0_.PORTLET_LOCATION_COLUMN as col_1_0_, portlet1_.PORTLET_URL as col_2_0_, portlet1_.PORTLET_TITLE as col_3_0_, portletloc0_.PORTLET_ID as col_4_0_ from JEDA_PORTLET_LOCATION portletloc0_, JEDA_PORTLET portlet1_ where portletloc0_.PORTLET_ID=portlet1_.PORTLET_ID and portletloc0_.POSITION_ID=?order by portletloc0_.PORTLET_LOCATION_ROW asc, portletloc0_.PORTLET_LOCATION_COLUMN asc

2011-3-4 9:33:18 org.apache.catalina.core.StandardWrapperValve invoke

severity: servlet.service () for Servlet DispatcherServlet threw exception

java.sqlexception: “MENU0_”.”MENU_OPEN_IN_HOME”: identifier is invalid

the reason:
The attribute name of the
hbm. XML file does not correspond to the attribute name of the database

SQL error: 17006, sqlstate: 99999 invalid column name

SQL Error: 17006, SQLState: 99999 invalid column name

reported an error when using hibernate for query today. This is simply recorded here.

problem description:

USES hibernate to query an entity for an error.

reason analysis:

	String sql = "select emplId,name  from employee";
	try {
		Session session = sessionFactory.getCurrentSession();
		SQLQuery query = session.createSQLQuery(sql.toString());			
		query.addScalar("emplId", StringType.INSTANCE);			
		query.addScalar("emplName", StringType.INSTANCE);
		query.setResultTransformer(Transformers.aliasToBean(Employee.class));
		employeeList = query.list();
		}
		......

The field for the

SQL query is name, and the field for the entity is emplName. Name inconsistency results.

solution:

	String sql = "select emplId, name as emplName from employee";
	try {
		Session session = sessionFactory.getCurrentSession();
		SQLQuery query = session.createSQLQuery(sql.toString());			
		query.addScalar("emplId", StringType.INSTANCE);			
		query.addScalar("emplName", StringType.INSTANCE);
		query.setResultTransformer(Transformers.aliasToBean(Employee.class));
		employeeList = query.list();
		}
		......