hibernate操作数据库的存储过程或函数

本文介绍了一个使用Java Hibernate框架进行数据库操作的测试类。该测试类通过Spring框架初始化,并展示了如何获取数据库实体及调用PostgreSQL中的自定义函数来删除特定记录。此示例涉及HibernateTemplate的使用、Spring依赖注入以及PostgreSQL存储过程的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.wm.daoTest;

import java.sql.CallableStatement;
import java.sql.Connection;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import com.wm.commune.entity.CommuneCategoryEntity;
import com.wm.dao.dynamic.CustomerContextHolder;
import com.wm.dao.dynamic.CustomerType;

public class DBFunctionTest {
	
	public ApplicationContext appContext;
	private HibernateTemplate hibernateTemplate;
	
	@Before
	public void before(){
		CustomerContextHolder.setCustomerType(CustomerType.COMMUNE_DB);
		appContext = new ClassPathXmlApplicationContext("spring/ApplicationContext-base.xml");
		hibernateTemplate = appContext.getBean(HibernateTemplate.class);
	}
	
	@Test
	public void testHibernate(){
		CommuneCategoryEntity comm = hibernateTemplate.get(CommuneCategoryEntity.class, 100000);
		System.out.println(comm);
	}

	@Test
	public void testFunction() throws Exception {
		Connection con = SessionFactoryUtils.getDataSource(hibernateTemplate.getSessionFactory()).getConnection();
		String procedure = "{call delete_category(?)}";
		CallableStatement cstmt = con.prepareCall(procedure);
		cstmt.setInt(1, 100000);
		int num = cstmt.executeUpdate();
		System.out.println(num);
	}
}

postgresql数据库中的函数为:

CREATE OR REPLACE FUNCTION delete_category(cid integer)
  RETURNS void AS
$BODY$
DECLARE rid integer;
begin
	select $1-$1%10000 into  rid;
	delete from wm_commune_category where id>rid;
end;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION delete_category(integer)
  OWNER TO wm_psql;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值