【Java 从 0 到架构师】Spring - 整合 MyBatis,大厂 Mysql 高频面试题
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
其他依赖:
必要:spring-context、mysql-connector-java、mybatis
可选:logback-classic、druid
===================================================================================
<context:property-placeholder location="db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<pr
operty name="driverClassName" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
数据源也可以使用:
Spring 的 DriverManagerDataSource
MyBatis 的 PooledDataSource
这里配置的连接池,默认会自动提交事务
整合 MyBatis - SqlSessionFactoryBean
=====================================================================================================
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.mj.domain"/>
<property name="mapperLocations">
<array>
<value>mappers/*.xml</value>
</array>
</property>
</bean>
整合 MyBatis - MapperScannerConfigurer
=======================================================================================================
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.mj.dao"/>
</bean>
配置完后可以通过 getBean 方法获取 dao 的代理对象,bean 的 id 是 dao 类名的小驼峰形式
比如 com.mj.dao.SkillDao 的 id 是 skillDao
SkillDao dao = ctx.getBean("skillDao", SkillDao.class);
=========================================================================
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
评论