public interface StudentService extends DAO<Student>,Cloneable { public StudentService clone() throws CloneNotSupportedException; } @Service("studentServiceBean") @Transactional public class StudentServiceBean extends DaoSupport<Student> implements StudentService { @Override public StudentService clone() throws CloneNotSupportedException { return (StudentService) super.clone(); } }
单元测试
public class MyTest { @Test public void testClone() { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); StudentService studentService = (StudentService) context.getBean("studentServiceBean"); StudentService newStudentService = null ; try { newStudentService = studentService.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } Student s = newStudentService.find(1); System.out.println(s == null); System.out.println(s instanceof HibernateProxy); System.out.println(s instanceof PersistentCollection); // Hibernate.initialize(s); // s.getTeacher().getUsername(); } }
这样便能实现接口和SpringBean的clone...clone的对象,操作与spring实例化对象一致,但现在的问题是,我并不清楚,clone出的对象,是否受到spring容器管理,也就是说,StudentService中的EntityManage,以及session这些是否由Spring容器关闭!
经过测试,得出,clone的SpringBean不受到Spring容器管理!!!我的想法失败了...
测试的方法是:
@Test public void testClone2(){ try { AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); EntityManagerFactory emf = (EntityManagerFactory) context.getBean("entityManagerFactory"); EntityManager em = emf.createEntityManager(); Student s1 = em.find(Student.class, 1); System.out.println(s1.getUsername()); // 关闭spring context.close(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } EntityManager em2 = emf.createEntityManager(); Student s2 = em2.find(Student.class, 1); System.out.println(s2.getUsername()); Student s3 = new Student("LUCY"); // em2.getTransaction().begin(); em2.persist(s3); // em2.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } }
注意注释的:em2.getTransaction().begin();与em2.getTransaction().commit();也是是spring容器管理的
结果sql返回:
Hibernate: select student0_.id as id0_0_, student0_.teacher_id as teacher3_0_0_, student0_.username as username0_0_ from Student student0_ where student0_.id=? Vicky Hibernate: select student0_.id as id0_0_, student0_.teacher_id as teacher3_0_0_, student0_.username as username0_0_ from Student student0_ where student0_.id=? Vicky
并未出现insert语句,表示该持久化操作并没有成功,查询数据库证实了这点.
修改注释的2条之后,返回增加了:
Hibernate: insert into Student (teacher_id, username) values (?, ?)