1. 程式人生 > 實用技巧 >Spring - 案例511:xml&註解 混合開發 整合MyBatis

Spring - 案例511:xml&註解 混合開發 整合MyBatis

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);
    }
}