11、整合Mybatis

步骤:

  1. 导入相关jar包
    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop织入
    • mybatis-spring
  2. 编写配置文件
  3. 测试

11.1、Mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

举个🌰:

首先先导入maven依赖

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</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>

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

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
  1. 实体类 User.java
    public class user {
       private int id;
       private String name;
       private String pwd;
    
       @Override
       public String toString() {
           return "user{" +
                   "id=" + id +
                   ", name='" + name + '\'' +
                   ", pwd='" + pwd + '\'' +
                   '}';
       }
    
       public int getId() {
           return id;
       }
    
       public void setId(int id) {
           this.id = id;
       }
    
       public String getName() {
           return name;
       }
    
       public void setName(String name) {
           this.name = name;
       }
    
       public String getPwd() {
           return pwd;
       }
    
       public void setPwd(String pwd) {
           this.pwd = pwd;
       }
    }
    
    
  2. 核心配置文件 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.yao.pojo"/>
       </typeAliases>
    
       <!--    用于指定使用哪个环境     default: 用于指定使用的环境id  -->
       <environments default="development">
           <!--     用于配置开发环境     id: 环境的唯一识别码    -->
           <environment id="development">
    
               <!--      事务管理器  type: 用于设置mybatis采用什么方式管理事务      JDBC表示采用和JDBC一样的事务管理方式    -->
               <transactionManager type="JDBC"/>
               <!--      数据源/连接池, 用于配置连接池和数据库连接的参数     type: 用于设置mybatis是否采用连接池技术      POOLED表示MyBatis采用连接池技术     -->
               <dataSource type="POOLED">
                   <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                   <property name="url"
                             value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
                   <property name="username" value="root"/>
                   <property name="password" value="rootroot"/>
               </dataSource>
           </environment>
       </environments>
    
       <mappers>
           <mapper class="com.yao.mapper.UserMapper"/>
       </mappers>
    
    </configuration>
    
  3. 编写接口 UserMapper
    public interface UserMapper {
    
       //无参
       public List<user> selectUser();
    
    //    普通方式传参
    //    public List<user> selectbuid(String user,String pwd);
    
       //使用注释传参
       public List<user> selectbyid(
               @Param("name")String user,
               @Param("pwd")String pwd
       );
    
    }
    
    
  4. 编写mapper.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
           PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.yao.mapper.UserMapper">
    
       <select id="selectUser" resultType="user">
           select * from mybatis.user;
       </select>
    
    <!--    普通传参-->
    <!--    <select id="selectbyid" parameterType="java.lang.String" resultType="user">-->
    <!--        select * from mybatis.user where id = #{id};-->
    <!--    </select>-->
    
    <!--    注释传参-->
       <select id="selectbyid" resultType="user">
           select * from mybatis.user
           where name=#{name} and pwd=#{pwd};
       </select>
    
    </mapper>
    
  5. 测试
    public class MyTest {
    
       @Test
       public void test() throws IOException {
           String resources = "mybatis-config.xml";
           InputStream in = Resources.getResourceAsStream(resources);
           SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
           SqlSession sqlSession = sessionFactory.openSession(true);
    
           UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
           System.out.println("无参");
           List<user> userAllList = mapper.selectUser();
           for (user user : userAllList) {
               System.out.println(user);
           }
    
           System.out.println("含参");
           List<user> userList = mapper.selectbyid("bbb","123123");
           for (user user : userList) {
               System.out.println(user);
           }
       }
    
    }
    

11.2、Mybatis-Spring

使用SqlSessionTemplate

  1. 实体类 user.java
    public class user {
       private int id;
       private String name;
       private String pwd;
    
       @Override
       public String toString() {
           return "user{" +
                   "id=" + id +
                   ", name='" + name + '\'' +
                   ", pwd='" + pwd + '\'' +
                   '}';
       }
    
       public int getId() {
           return id;
       }
    
       public void setId(int id) {
           this.id = id;
       }
    
       public String getName() {
           return name;
       }
    
       public void setName(String name) {
           this.name = name;
       }
    
       public String getPwd() {
           return pwd;
       }
    
       public void setPwd(String pwd) {
           this.pwd = pwd;
       }
    }
    
  2. mybatis配置文件 mybatis-config.xml (可以都写在mybatis-Spring 的配置文件中)
    <?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.yao.pojo"/>
       </typeAliases>
    
    </configuration>
    
  3. mybatis-spring 配置文件 spring-dao.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
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
       <!--    DataSource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid-->
       <!--    我们这里使用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/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
           <property name="username" value="root"/>
           <property name="password" value="rootroot"/>
       </bean>
    
    <!--    sqlSessionFactory
       需要注入一个数据源、绑定一个mybatis
    -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--        数据源dataSource-->
           <property name="dataSource" ref="dataSource"/>
    <!--        绑定mybatis-->
           <property name="configLocation" value="classpath:mybatis-config.xml"/>
           <property name="mapperLocations" value="classpath:com/yao/mapper/UserMapper.xml"/>
       </bean>
    
    <!--    sqlSessionTemplate 就是我们在mybatis使用的sqlsession-->
       <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--        只能使用构造去进行注入sqlsessionFactory-->
           <constructor-arg index="0" ref="sqlSessionFactory"/>
       </bean>
    
       <bean id="userMapper" class="com.yao.mapper.UserMapperImpl">
           <property name="sqlSessionTemplate" ref="sqlSession"/>
       </bean>
    </beans>
    
  4. 接口 UserMapper
    public interface UserMapper {
    
       public List<user> selectUser();
    
       public user selectbyid(
               @Param("name")String name,
               @Param("pwd")String pwd
       );
    
    }
    
  5. 编写mapper.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
           PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.yao.mapper.UserMapper">
    
       <select id="selectUser" resultType="user">
           select * from mybatis.user;
       </select>
    
       <!--    普通传参-->
       <!--    <select id="selectbyid" parameterType="java.lang.String" resultType="user">-->
       <!--        select * from mybatis.user where id = #{id};-->
       <!--    </select>-->
    
       <!--    注释传参-->
       <select id="selectbyid" resultType="user">
           select id from mybatis.user
           where name=#{name} and pwd=#{pwd};
       </select>
    
    </mapper>
    
  6. 接口实现类 UserMapperImpl.java
    public class UserMapperImpl implements UserMapper {
    
       private SqlSessionTemplate sqlSessionTemplate;
    
       public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
           this.sqlSessionTemplate = sqlSessionTemplate;
       }
    
       public List<user> selectUser() {
           UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
           return mapper.selectUser();
       }
    
       public user selectbyid(String name, String pwd) {
           UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
           return mapper.selectbyid(name, pwd);
       }
    
    }
    
  7. 测试
    @Test
       public void test1(){
           ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
           UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    
           List<user> select = userMapper.selectUser();
           for (user user : select) {
               System.out.println(user);
           }
    
           System.out.println();
           user aaa = userMapper.selectbyid("aaa", "123123");
           System.out.println(aaa);
       }
    

使用SqlSessionDaoSupport

之后接口实现类的代码进行了部分的改变,其余的类个配置文件的代码均未改变

UserMapperImpl1.java

public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper {

    public List<user> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }

    public user selectbyid(String name, String pwd) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectbyid(name,pwd);
    }
}

实现原理:让UserMapperImpl1类继承SqlSessionDaoSupport类,SqlSessionDaoSupport类包含getSqlSession(),可以直接调用这个方法得到sqlSession,但需要通过在spring-dao.xml里添加

<bean id="userMapper1" class="com.yao.mapper.UserMapperImpl1">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

将sqlSessionFactory参数传递过去,这样我们就得到了slqSession,后续的代码与之前一样。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇