技术开发 频道

Spring与Hibernate的整合与解耦

   二,在代码中获取组织Service。
public class 组织ServiceTest extends TestCase { private 组织Service 组织Service; protected void setUp() throws Exception { String[] configLocation = new String[] { "/web/WEB-INF/training-service.xml", "/web/WEB-INF/training-data.xml" }; ApplicationContext ac = new FileSystemXmlApplicationContext(configLocation); 组织Service = (组织Service)ac.getBean("组织Service"); } public void testGet组织By名称() { System.out.println("get组织By名称"); 组织 组织 = 组织Service.增加组织(new 组织("aaa")); 组织 = 组织Service.get组织By名称("aaa"); assertEquals("aaa", 组织.get名称()); 组织 = 组织Service.get组织By名称("abc"); assertNull(组织); } }
    三,组织DaoImpl的代码:
/*
* @param 组织名称
* @return 组织 或者 null
*/
public 组织 get组织By名称(String 组织名称) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction(); //Hiberante3.1以后的代码

组织 组织 = (组织)session.createQuery("from 组织 c where c.名称 = '" + 组织名称 + "'")
.uniqueResult();

session.getTransaction().commit();

return 组织;
}
    由上可见,Hibernate的核心代码一点未变,从而在与Spring整合的基础上,实现了与Spring的解耦。
0
相关文章