spring hibernate struts 整合开发(2)

编程技术  /  houtizong 发布于 3年前   63
一. spring hibernate struts 整合开发(1) - 搭建环境
二. spring hibernate struts 整合开发(2) - Spring集成的Hibernate编码和测试
三. spring hibernate struts 整合开发(3) - Struts集成Spring
四. spring hibernate struts 整合开发(4) - Struts与Spring集成2
五. spring hibernate struts 整合开发(5) - Hibernate二级缓存
六. spring hibernate struts 整合开发(6) - 额外功能


Spring集成的Hibernate编码与测试

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

@Transactionalpublic 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; @BeforeClasspublic static void setUpBeforeClass() throws Exception {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");personService = (PersonService)ctx.getBean("personService");}@Testpublic void testSave() throws UnsupportedEncodingException {Person person = new Person();person.setName("John");personService.save(person);}@Testpublic void testUpdate() {Person person = personService.getPerson(1);person.setName("Lisa");personService.update(person);}@Testpublic void testGetPerson() {Person person = personService.getPerson(1);System.out.println(person.getName());}@Testpublic void testDelete() {personService.delete(1);}@Testpublic void testGetPersons() {List<Person> persons = personService.getPersons();for (Person p : persons)System.out.println(p.getName());}


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

整理自:传智播客spring教程

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客