mysql 5.0存贮过程 调用

来源:互联网 发布:通假字 错别字 知乎 编辑:程序博客网 时间:2024/05/16 16:00

Hibernate中使用Mysql存储过程
1、我使用了mysql-connector-java-5.0.0-beta-bin.jar(其实用老的mysql-connector-java-3.1.8-bin.jar也可以调用存储过程的)这个最新的mysql驱动。
2、数据库我使用了mysql-5.0.18-win32,安装后建立了一个简单的数据表。
sql如下:


create database testprocedure;
use testprocedure;
create table testtable (id int(11) AUTO_INCREMENT, content varchar(255), readcount int(11) DEFAULT 0,primary key (id));
desc testtable;(查看是否建立正确)


3、建立一个专用的用户(可选,建立时请使用具有grant权限的用户如root):


grant select,delete,update,create,alter,execute on testtable.* to testprocedure@"localhost" identified by "test";

用户名为testprocedure,密码test。注意权限中的execute,它就是执行call procedure的权限。在你的Hibernate配置中使用该帐户。
4、建立一个存储过程:
sql如下:

java代码: 

delimiter //
(注意//是新的命令结束符,方便我们建立procedure)
create procedure readcountplusone (inputid int)
begin
update testtable set readcount = readcount + 1 where id = inputid;
end//
(建立存储过程完毕)
delimiter ;
(恢复命令结束符为;)

5、测试一下存储过程:

java代码: 

insert into testtable values (null,'test',0);
select * from testtable;
call readcountplusone(1);
select * from testtable;

应该看到原先readcount为0,call以后变成1,而且每次call都加1。
如果执行有错,可以删除procedure重新建立。
删除的命令为drop procedure readcountplusone;
6、开始在我们的Hibernate+Spring support项目中使用procedure:
HBM映射我们不说了,这里没有使用named query。Hibernate+Spring的配置这里也不多说了,应该可以搜寻到很多文章。
我的DAO是extends HibernateDAO,具体的使用方法可以参照其他很多讲Spring hibernate support的文章。
我们建立一个方法,比较丑陋(只是测试,大家有好方法可以提),假设对应testtable的pojo为TestPojo,它的getId()返回id对应的值:

java代码: 

public void readCountPlusOne(final TestPojo pojo) {
        getHibernateTemplate().execute(new HibernateCallback() {
                public Object doInHibernate(Session session) {
                    try {
                        Connection conn = session.connection();

                        String sql = "{call readcountplusone(?)}";
                        CallableStatement stmt = conn.prepareCall(sql);
                        stmt.setLong(1, pojo.getId().longValue());
                        stmt.execute();
                    } catch (Exception e) {
                        if(log.isDebugEnable){
                                log.debug("call DAO
's readCountPlusOne() faild, with Exception:");
                                e.printStackTrace();
                        }
                    }

                    return null;
                }
            });
    }

7、然后我们在我们的bussiness中调用readCountPlusOne方法既可实现通过Hibernate调用一个简单的Mysql存储过程。