mysql 5.0存貯過程 調用

來源:互聯網
上載者:User

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預存程序。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.