时间:2021-07-01 10:21:17 帮助过:3人阅读
其中以下部分声明的是数据源,目前常用的有dbcp或者C3P0的数据源,内层则为数据库连接的各项参数。
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/> <property name="username" value="root"/> <property name="password" value="123456"/>
</bean>
以下部分为hibernate的sessionFactory注入配置
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>student.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true </value> </property> </bean>
其实现类为Spring自带的org.springframework.orm.hibernate4.LocalSessionFactoryBean ( 这里我用的Spring 4.X版本);
dateSource为上述配置中的数据源;
student.hbm.xml则为hibernate的一个单表映射文件。
hibernateProperties中可以配置hibernate对应的属性,如方言dialect、sql显示show_sql等。
2、Dao层实现
package com.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.vo.Student; public class UserDaoImpl implements UserDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void save(Student student) { Session session = sessionFactory.openSession(); session.getTransaction().begin(); session.save(student); System.out.println("excute save;"); session.getTransaction().commit(); } @Override public void delete() { System.out.println("excute delete;"); } }
3、将Dao层注入进Service层,实现如下:
package com.service; import com.dao.UserDao; import com.vo.Student; public class UserService { private UserDao dao; public void setDao(UserDao dao) { this.dao = dao; } public void save(){ Student student = new Student(2, "test2", 30); dao.save(student); } }
简单测试如下:
package com.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.UserService; public class TestAopAnnotation { @Test public void testAopAnnotation(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); UserService service = (UserService) context.getBean("userService"); service.save(); } }
测试结果:
Spring学习4_整合Hibernate进行数据库操作
标签: