1. JDBCTemplate(spring框架自带)
使用方式:1.通过在xml文件中引用
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置 c3p0 数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="initialPoolSize" value="${initPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
-------------------------------------------------------------------------------------------
<!-- 配置 spring 的 JdbcTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>//第一个dataSource指jdbcTemplate的属性,第二个是引用的c3p0的配置
</bean>
在需要的地方使用(或注入)即可。
使用的方式有两种一种是通过注入的方式,另外一种是获取bean对象
bean对象的方式:
private ApplicationContext ctx= null;
private JdbcTemplate jdbcTemplate = null;
{
ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
}
注入的方式:
在xml文件中添加包扫描配置:
<context:component-scan base-package="com.atguigu.spring.jdbc"></context:component-scan>
在代码中使用注解:
@Autowired
private JdbcTemplate jdbcTemplate;
更加详细请参考推荐文章
推荐文章:https://blog.csdn.net/u013468917/article/details/52217954
2.Hibernate访问数据库 之 HibernateDaoSupport
使用的步骤:
1.dao实现类继承HibernateDaoSupport
2.配置sessionFactory
3.将sessionFactory注入到dao实现类中
dao实现类要访问数据库需要Hibernate的 sessionFactory
dao层获取sessionFactory有两种方法:
1.在spring的配置文件中配置dao实现类的bean,在bean中引用sessionFactory。
2.使用注解的方式。在spring配置文件中扫描包,并使用注解注入
推荐文章:https://blog.csdn.net/hx18652266251/article/details/57127104