8 import org.springframework.transaction.annotation.Propagation;
9 import org.springframework.transaction.annotation.Transactional;
10
11 import com.b510.domain.Person;
12 import com.b510.service.PersonService;
13
14 /**
15 * 使用注解方式进行事务管理
16 *
17 * @author Hongten
18 *
19 */
20 @Transactional
21 public class PersonServiceBean implements PersonService {
22 /**
23 * 通过bean.xml配置文件按名称sessionFactory注入属性sessionFactory,
24 * 当sessionFactory注入成功后,我们可以得到Session对象
25 */
26 @Resource
27 private SessionFactory sessionFactory;
28
29 @Override
30 public void delete(Integer id) {
31 sessionFactory.getCurrentSession().delete(
32 sessionFactory.getCurrentSession().load(Person.class, id));
33 }
34
35 // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
36 @Override
37 @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
38 public Person getPerson(Integer id) {
39 return (Person) sessionFactory.getCurrentSession()
40 .get(Person.class, id);
41 }
42
43 // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
44 @Override
45 @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
46 @SuppressWarnings("unchecked")
47 public List
48 return sessionFactory.getCurrentSession().createQuery("from Person")
49 .list();
50
51 }
52
53 @Override
54 public void save(Person person) {
55 sessionFactory.getCurrentSession().persist(person);
56 }
57
58 @Override
59 public void update(Person person) {
60 sessionFactory.getCurrentSession().merge(person);
61 }
/spring+hibernate/src/com/b510/test/PersonServiceBeanTest.java
1 package com.b510.test;
2
3 import org.junit.BeforeClass;
4 import org.junit.Test;
5 import org.springframework.context.ApplicationContext;
6 import org.springframework.context.support.ClassPathXmlApplicationContext;
7
8 import com.b510.domain.Person;
9 import com.b510.service.PersonService;
10
11 public class PersonServiceBeanTest {
12 static PersonService personService;
13
14 @BeforeClass
15 public static void setUpBeforeClass() throws Exception {
16
17 try {
18 ApplicationContext act = new ClassPathXmlApplicationContext(
19 "bean.xml");
20 personService = (PersonService) act.getBean("personService");
21 } catch (Exception e) {
22 e.printStackTrace();
23 }
24 }
25
26 @Test
27 public void testSave() {
28 personService.save(new Person("hongten", 21, "男"));
29 }
30
31 @Test
32 public void testUpdate() {
33 Person person =personService.getPerson(2);
34 person.setName("hanyuan");
35 person.setAge(21);
36 person.setSex("男");
37 personService.update(person);
38 }
39
40 @Test
41 public void testGetPersonInteger() {
42 Person person = personService.getPerson(1);
43 System.out.println(person.getId() + " " + person.getName() + " "
44 + person.getAge() + " " + person.getSex());
45 }
46
47 @Test
48 public void testGetPerson() {
49 java.util.List
50 System.out.println("*******************");
5