Spring整合Mybatis常用配置
阿新 • • 發佈:2022-03-29
spring-mybatis.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" > <!--Spring整合mybatis方法一--> <!--DataSource:使用spring的資料來源替換Mybatis的配置--> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT" /> <property name="username" value="root" /> <property name="password" value="6113081" /> </bean> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource" /> <!--繫結mybatis配置檔案--> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!--設定mapper對映路徑--> <property name="mapperLocations" value="classpath:com/zhang/mapper/*.xml" /> </bean> <!--SqlSessionTemplate就是我們使用的sqlSession,該方法需要我們傳入一個sqlSessionFactory也就是上面的--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--此處只能使用構造器注入sqlSessionFactory,因為SqlSessionTemplate類沒有set方法--> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> </beans>
mybatis-config.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> <!-- 配置別名--> <typeAliases> <package name="com.zhang.pojo"/> </typeAliases> <!--設定--> </configuration>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" > <import resource="spring-dao.xml" /> <bean id="userMapper" class="com.zhang.mapper.UserMapperImpl" > <property name="sqlSession" ref="sqlSession" /> </bean> </beans>