当先锋百科网

首页 1 2 3 4 5 6 7

1 整合Mybatis

步骤:

  • 导入相关jar包
    junit
    mybatis
    mysql数据库
    spring相关的
    aop织入
    mybatis-spring【new】
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-study</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-10-mybatis_spring</artifactId>

     <dependencies>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.12</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>8.0.19</version>
         </dependency>
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
             <version>3.5.2</version>
         </dependency>
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
             <version>5.1.9.RELEASE</version>
         </dependency>
<!--         spring要操作数据库的话,还需要一个Spring-jdbc-->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-jdbc</artifactId>
             <version>5.1.9.RELEASE</version>
         </dependency>

         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjweaver</artifactId>
             <version>1.8.13</version>
         </dependency>

         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis-spring</artifactId>
             <version>2.0.5</version>
         </dependency>

     </dependencies>

</project>
  • 编写配置文件
  • 测试

1.1回忆mybatis

1.编写实体类

package com.lwq.pojo;

import lombok.Data;

/**
 * @author
 * @since 2020/6/16 18:20
 */

@Data
public class User {
    private  int id;
    private  String name;
    private  String pwd;
}

2.编写核心配置文件

<?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核心配置文件-->
<configuration>

    <typeAliases>
        <package name="com.lwq.pojo"/>

    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!--            事务管理,jdbc-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="147258"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/lwq/mapper/UserMapper.xml"></mapper>
    </mappers>


</configuration>

3.编写mybatis工具类

package com.lwq.utlis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//SqlSessionFactory-->SqlSession
public class MybatisUtils {


    private static InputStream inputStream = null;

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            //使用Mybatis第一步:获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}


4.编写接口

package com.lwq.mapper;

import com.lwq.pojo.User;

import java.util.List;

/**
 * @author
 * @since 2020/6/16 18:55
 */
public interface UserMapper {
    //查询所有的学生信息
    public List<User> selectUser();
}

5.编写Mapper.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">

<!--        namespace=绑定一个对应的Dao接口/Mapper接口-->
<mapper namespace="com.lwq.mapper.UserMapper">
    <!--    select查询语句-->
    <!--    resultType返回的结果集    -->
    <select id="selectUser" resultType="com.lwq.pojo.User">
    select * from mybatis.user
  </select>

</mapper>

6.测试

import com.lwq.mapper.UserMapper;
import com.lwq.pojo.User;
import com.lwq.utlis.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @author
 * @since 2020/6/16 19:05
 */
public class MyTest {

    @Test
    public  void selectUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();

    }
}

注意:需要在我们的pom.xml加上

 <!--    在build中配置resources,来防止我们出现资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

1.2:Mybatis-spring

第一步:编写数据源配置
第二步:编写sqlSessionFactory
第三步:SqlSessionTemplate

<?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"
       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/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/context/spring-aop.xsd">
    <!--    sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:com/lwq/mapper/UserMapper.xml"></property>
    </bean>


    <!--    DataSource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
            我们这里使用spring的JDBC
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT"></property>
        <property name="password" value="147258"></property>
        <property name="username" value="root"></property>
    </bean>


    <!--    SqlSessionTemplate就是我们使用的sqlSession-->
    <bean id="SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

        <!--        只能使用构造器注入sqlSessionFactory,因为他没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

</beans>

第四步:需要给接口加实现类

package com.lwq.mapper;

import com.lwq.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

/**
 * @author
 * @since 2020/6/16 20:00
 */
public class UserMapperImpl implements  UserMapper {

//    在原来 我们的所有操作都 SqlSession 来执行  现在都使用 SqlSessionTemplate
    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> selectUser() {


        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
       return mapper.selectUser();


    }
}

第五步:将自己写的实现类,注入到Spring中

<?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"
       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/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/context/spring-aop.xsd">


    <import resource="beans.xml"></import>


<!--    <import resource="spring-mvc.xml"></import>-->

    <bean id="userMapper" class="com.lwq.mapper.UserMapperImpl">
        <!--        由于我们UserMapperImpl需要注入SqlSessionTemplate我们就可以注入-->
        <property name="sqlSessionTemplate" ref="SqlSessionTemplate"></property>
    </bean>
</beans>

第六步:测试即可

import com.lwq.mapper.UserMapperImpl;
import com.lwq.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @author
 * @since 2020/6/16 19:05
 */
public class MyTest {

    @Test
    public  void selectUser(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapperImpl mapper = (UserMapperImpl) context.getBean("userMapper");
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }

    }
}


SqlSessionTemplate 介绍:
SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。SqlSessionTemplate 是线程安全的,可以被多个 DAO 或映射器所共享使用。

还有第二种方式:
使用SqlSessionDaoSupport
SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate

1.编写实现类(接口不用重新编写)

package com.lwq.mapper;

import com.lwq.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

/**
 * @author
 * @since 2020/6/16 20:40
 */
public class UserMapperImpl2 extends SqlSessionDaoSupport implements  UserMapper {
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return  mapper.selectUser();

    }
}

2.注入spring

 <bean id="userMapper2" class="com.lwq.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

3.测试

 @Test
    public  void selectUser2(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapperImpl2 mapper = (UserMapperImpl2) context.getBean("userMapper2");
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }

    }