往期文章:
Spring 学习总结笔记【一、快速入门】
Spring 学习总结笔记【二、IoC-控制反转】
Spring 学习总结笔记【三、注解开发】
Spring 学习总结笔记【四、整合Junit】
Spring 学习总结笔记【五、配置数据源】
现在,我们直接按原生方式使用 MyBatis 。
自定义一个Dao层,使用Mybatis的注解开发
public interface AccountDao {
@Insert("insert into tbl_account(name, money) values (#{name}, #{money})")
void save(Account account);
@Delete("delete from tbl_account where id=#{id}")
void delete(Integer id);
@Update("update tbl_account set name = #{name}, money = #{money} where id = #{id}")
void update(Account account);
@Select("select * from tbl_account")
List<Account> findAll();
@Select("select * from tbl_account where id = #{id}")
Account findById(Integer id);
}
测试代码:
public static void main(String[] args) throws IOException {
// 1. 创建SqlSessionFactoryBuilder 对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 2. 加载xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 3.创建 SqlsessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 4.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 5.执行sqlSession对象执行查询,获取结果User
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
Account account = accountDao.findById(1);
System.out.println(account);
// 6.释放资源
sqlSession.close();
}
- 将Mybatis中的实例交给Spring管理,Spring通过单例方式来管理
SqlSessionFactory
。- Mybatis中SqlSessionFactory的创建是通过SqlSessionFactoryBuilder来创建实例化,在Mybatis和Spring的整合后,通过
SqlSessionFactoryBean
来替代,SqlSessionFactoryBean必须给定一个属性dataSource
。- 给定一个属性
configLocation
,用来指定Mybatis的xml核心配置文件。
对于mybatis执行sql语句,需要用到的对象有:
SqlSessionFactory
对象:只有创建了SqlSessionFactory对象,才能调用openSession()方法得到SqlSession对象。dao
接口的代理对象:例如AccountDao接口,需要的代理对象为:SqlSeesion.getMapper(AccountDao.class)。DataSource
对象:使用一个更强大、功能更多的连接池对象代替Mybatis自己的PooledDataSource。
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
jdbc.username=root
jdbc.password=****
创建mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
configuration>
spring-jdbc.xml
<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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
bean>
beans>
创建applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="spring-jdbc.xml"/>
<bean id="accountDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.tyt.dao.AccountDao"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
bean>
beans>
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao = (AccountDao) app.getBean("accountDao");
System.out.println(accountDao);
Account ac = accountDao.findById(1);
System.out.println(ac);
}
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setTypeAliasesPackage("com.tyt.domain");
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerRegistrar(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.tyt.dao");
return msc;
}
}
Mybatis配置类主要是将原Mybatis配置文件的
以及
标签中的内容替换。
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String name;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(name);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
@Configuration
@ComponentScan({"com.tyt"})
@PropertySource({"jdbc.properties"})
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = app.getBean(AccountService.class);
Account account = accountService.findById(1);
System.out.println(account);
}