Spring—基于XML配置整合
spring基于XML配置文件整合,就是把myBatis涉及的相关技术关键类对象存入spring容器中并管理。
整合的思路:
编写jdbc.properties文件–>pom文件导入依赖包–>applicationContext.xml文件配置bean
一、spring整合数据库连接
1、导入依赖
<!--1.数据库连接池Druid-->
<artifactId>druid</artifactId>
<!--2.mySQL连接-->
<artifactId>mysql-connector-java</artifactId>
<!--3.jdbc连接-->
<artifactId>spring-jdbc</artifactId>
2、XML配置
<!--1.加载数据库连接配置文件-->
<context:property-placeholder location="classpath:*.properties"/>
<!--2.加载数据库连接池配置文件-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
二、spring整合myBatis
1、导入依赖
<!--4.mybatis组件-->
<artifactId>mybatis</artifactId>
<!--5.spring整合mybatis-->
<artifactId>mybatis-spring</artifactId>
<!--6.spring组件-->
<artifactId>spring-context</artifactId>
2.XML配置
<!--3.mybatis需要的SqlSession工厂对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.mybatis需要mapper动态代理对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mine.dao"/>
</bean>
<!--5.注入业务层对象和持久层对象-->
<bean id="accountService" class="com.mine.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
三、spring基于XML配置开发
1、实体类:根据数据库表,遵循ORM映射关系创建,并实现序列化。
//实体类,并实现序列化,提供set注入
public class Account implements Serializable {
private Integer id;
public void setId(Integer id) {
this.id = id;
}
}
2、持久层:编写CRUD接口方法,并编写映射配置文件。
//持久层接口
public interface AccountDao {
void delete(Integer id);
}
//持久层接口映射配置文件
<delete id="delete" parameterType="int">
delete from account where id = #{id}
</delete>
3、业务层:调用持久层,并编写实现类
//业务层接口
public interface AccountService {
void delete(Integer id);
}
//业务层接口实现类
public class AccountServiceImpl implements AccountService {
//引入持久层对象,并提供set注入
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
}
4、Demo测试
public class App {
public static void main(String[] args) {
//创建spring上下文对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取业务层接口对象
AccountService accountService = (AccountService) ctx.getBean("accountService");
//调用业务层方法
accountService.delete(1);
}