Hbernate getHibernateTemplate 增删改查

package com.test.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.test.bean.Test2;
import com.test.dao.SessionTestDao;

public class SessionTestDaoImpl extends HibernateDaoSupport implements SessionTestDao{
	private SessionTestDao sessionTestDao;
	
	public void setSessionTestDao(SessionTestDao sessionTestDao) {
		this.sessionTestDao = sessionTestDao;
	}

	public void testInsert() {
		try {
			SimpleDateFormat  format1 = new SimpleDateFormat("yyyy-MM-dd");
			Test2 entity = new Test2();
			entity.setC2("B1");
			entity.setC3(new Date());

			this.getHibernateTemplate().save(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void testUpdate() {
		Test2 entity = new Test2();
		entity.setC1(647915883);//更新id为647915883的记录,hibernate会根据ID查找这条记录
		entity.setC2("UpdateB1");
		entity.setC3(new Date());
		
		getHibernateTemplate().update(entity);    
	}

	public void testDeleted() {
		Test2 entity = new Test2();
		entity.setC1(647915883);//删除id为647915883的记录,hibernate会根据ID查找这条记录并删除
		entity.setC2("Update");
		entity.setC3(new Date());
		
		getHibernateTemplate().delete(entity);
	}

	public void testSelectById() {
		//load方式检索不到的话会抛出org.hibernate.ObjectNotFoundException异常
		// org.hibernate.LazyInitializationException: could not initialize proxy - no Session 设置 lazy="false"
		Test2 info = (Test2)getHibernateTemplate().load(Test2.class, 647915885L);
		//Test2 info = (Test2)getHibernateTemplate().get(Test2.class, 647915885L);
		System.out.println(info.getC1()+"\t"+info.getC2());
	}
	
	public static void main(String[] args){
		ApplicationContext context = new FileSystemXmlApplicationContext("/WebContent/WEB-INF/applicationContext.xml");
		SessionTestDao test = (SessionTestDao) context.getBean("sessionTestDao");// 括号写需要测试的bean id;

		//test.testInsert();
		//test.testUpdate();
		//test.testDeleted();
		test.testSelectById();
	}

}

 

你可能感兴趣的:(Hbernate getHibernateTemplate 增删改查)