hibernate mysql存储过程,Spring+Hibernate中使用Mysql存储过程初步

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如下:

java代码:

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):

java代码:

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存储过程。

有点走马观花,主要是把口舌都放在mysql部分,hibernate部分则用的比较简单,我想把调用方法改为Named Query,这样不会这么丑陋。

抛砖引玉,谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值