spring整合mybatis

首先先导包

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.8</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7.M3</version>
</dependency>

1、配置文件的方式整合

创建一个mybatis-config.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

	<!--配置数据源,使用spring中的jdbc-->
    <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/testdb?useUnicode=true&amp;characterEncoding=UTF8&amp;userSSL=true&amp;serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value="tx123"/>
     </bean>

	<!--将sqlSessionFactory注册到spring中-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:cn/butcher/mapper/*.xml"/>
        <property name="typeAliasesPackage" value="cn.butcher.pojo"/>
    </bean>
    
	<!--将sqlSession注册到spring中-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

好了,测试一下:

@Test
    public void test02(){
        ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-config.xml");
        SqlSession sqlSession = context.getBean("sqlSession", SqlSession.class);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

结果如下:
User{username=‘张三’, pwd=‘zs123456’, sex=1}
User{username=‘李四’, pwd=‘ls123’, sex=1}
User{username=‘王婶’, pwd=‘ws123’, sex=0}
User{username=‘谭熙’, pwd=‘tx123’, sex=1}

上一篇:order by和group by


下一篇:Oracle DG(Data Guard)支持异构平台说明