Integrate Hibernate3 with Spring
Integrate Hibernate3 with Spring
Like integrating Jdbc, Spring integrated Hibernate3 provides templates so that we only need to care about data table operations. when resources are closed and opened, and exceptions are handled by Spring, this template is HibernateTemplate. HibernateTemplate (DAO Support class) is obtained through SessionFactory, so let's take a look at how to configure SessionFactory in XML.
// Data Source
"DataSource"Class = "Org. springframework. jdbc. datasource. DriverManagerDataSource">
"DriverClassName"Value = "Com. mysql. jdbc. Driver">
"Url"Value = & Quot; jdbc: mysql: // localhost: 3306/dataBase & quot">
"Username"Value = "Root">
"Password"Value = "">
// SessionFactory Bean
Beanid ="SessionFactory"Class ="Org. springframework. orm. hibernate3.LocalSessionFactoryBean">
// Data Source
"DataSource">
"DataSource"/>
// Other attributes, such as dialect and whether to print SQL ....
"HibernateProperties">
"Hibernate. dialect">
Org. hibernate. dialect. MySQLDialect
// Ing File
"MappingResources">
Hibernate/Users. hbm. xml
In an application, you can use SessionFactory sf = getBean ("sessionFactory", SessionFactory. class );
HibernateTemplate ht = new HibernateTemplate (sf );
Then operate the table through HibernateTemplate.
ApplicationContextac =NewClassPathXmlApplicationContext ("applicationContext. xml ");
SessionFactorysessionFactory = ac. getBean ("sessionFactory", SessionFactory.Class);
HibernateTemplate ht =NewHibernateTemplate (sessionFactory );
Users user =NewUsers ();
User. setUname ("zhangsan ");
User. setAge (1 );
Ht. save (user );
We can see that this operation omits the opening and closing of resources and handles exceptions.