Spring - 案例513:xml&注解 混合开发 整合MyBatis
1 pom.xml添加相关坐标
2 实体类 Account + 数据库对应表
3 数据层 AccountDao接口
public interface AccountDao {
@Select("select * from account")
public List<Account> findAll();
}
4 业务层
// AccountService
public interface AccountService {
public List<Account> findAll();
}
// AccountServiceImpl
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List<Account> findAll() {
return accountDao.findAll();
}
}
5 配置文件 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1. 开启spring注解包扫描-->
<context:component-scan base-package="com.itheima"/>
<!--1.引入外部配置文件-->
<context:property-placeholder location="classpath:jdbc.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>
<!--3.Mybatis 整合 Spring-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--配置别名, 类名就是别名, 不区分大小写-->
<property name="typeAliasesPackage" value="com.itheima.domain"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
</bean>
</beans>
6 配置文件 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=1234
7 测试类
public class App {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService service = (AccountService) app.getBean("accountService");
List<Account> all = service.findAll();
System.out.println(all);
}
}