spring hibernate struts 整合开发(2)

一.springhibernatestruts整合开发(1)-搭建环境

二.springhibernatestruts整合开发(2)-Spring集成的Hibernate编码和测试

三.springhibernatestruts整合开发(3)-Struts集成Spring

四.springhibernatestruts整合开发(4)-Struts与Spring集成2

五.springhibernatestruts整合开发(5)-Hibernate二级缓存

六.springhibernatestruts整合开发(6)-额外功能

Spring集成的Hibernate编码与测试

1.新建一个业务bean:com.john.service.impl.PersonServiceBean

@Transactional
public class PersonServiceBean implements PersonService {
	@Resource private SessionFactory sessionFactory;
	
	public void save(Person person) {
		sessionFactory.getCurrentSession().persist(person);
	}
	
	public void update(Person person) {
		sessionFactory.getCurrentSession().merge(person);
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED, readOnly=true)
	public Person getPerson(Integer id) {
		return (Person)sessionFactory.getCurrentSession().get(Person.class, id);
	}
	
	public void delete(Integer id) {
		sessionFactory.getCurrentSession().delete(
				sessionFactory.getCurrentSession().load(Person.class, id));
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED, readOnly=true)
	public List<Person> getPersons() {
		return sessionFactory.getCurrentSession().createQuery("from Person").list();
	}

a.sessionFactory是通过@Resource来注入的,所以在beans.xml中必须有<context:annotation-config/>

b.getXXX方法不需要事务,并且是只读的

2.新建一个jUnit测试类:junit.test.PersonServiceTest

public class PersonServiceTest {
	private static PersonService personService; 
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		personService = (PersonService)ctx.getBean("personService");
	}

	@Test
	public void testSave() throws UnsupportedEncodingException {
		Person person = new Person();
		person.setName("John");
		personService.save(person);
	}

	@Test
	public void testUpdate() {
		Person person = personService.getPerson(1);
		person.setName("Lisa");
		personService.update(person);
	}

	@Test
	public void testGetPerson() {
		Person person = personService.getPerson(1);
		System.out.println(person.getName());
	}

	@Test
	public void testDelete() {
		personService.delete(1);
	}

	@Test
	public void testGetPersons() {
		List<Person> persons = personService.getPersons();
		for (Person p : persons)
			System.out.println(p.getName());
	}

对bean的方法分别进行测试。

整理自:传智播客spring教程

相关推荐