Spring + MyBatis + MySQL 整合

1、jar包

mybatis-3.4.1.jar、mybatis-spring-1.3.0.jar、mysql-connector-java-5.1.18-bin.jar、spring++

2、beans.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
    <!--引入db配置文件-->
    <context:property-placeholder location="classpath:db.properties" />
    <!--建立数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>

    <!--把sqlSessionFactory注入dao层-->
    <bean id="adminDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="win.muycode.dao.AdminDao"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

</beans>
3、mybatis.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置这里的别名,则mapping.xml文件中的resultType可以不用写全限定名-->
    <!--<typeAliases>
        <typeAlias type="win.muycode.domain.Admin" alias="Admin"/>
    </typeAliases>-->
    
    <!-- 映射配置文件 -->
    <mappers>
        <mapper resource="win/muycode/mapper/AdminMapping.xml"/>
    </mappers>
</configuration>
4、AdminMapping.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="win.muycode.dao.AdminDao">
    <!--id要与AdminDao的方法相同-->
    <select id="getAdminForId" resultType="win.muycode.domain.Admin" parameterType="java.lang.Integer">
        select * from wechat_admin where adminid=#{adminid}
    </select>
</mapper>
5、Test.java编写
public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        AdminDao ad = (AdminDao)ac.getBean("adminDao");
        Admin admin = ad.getAdminForId(1);
        System.out.println(admin.toString());
}

发表评论

Blue Captcha Image
Refresh

*