Spring整合mybatis完整示例

Spring整合mybatis完整示例Spring整合mybatis完整示例  实现功能:根据id查找用户信息。 1、首先创建一个与表中数据相对应的实体类,User.javapackagebean;publicclassUser{intid;Stringname;intage;Stringsex;Stringschool;pu…

大家好,又见面了,我是你们的朋友全栈君。

Spring整合mybatis完整示例

 

 

实现功能:根据id查找用户信息。

 

1、首先创建一个与表中数据相对应的实体类,User.java

package bean;

public class User {
    int id;
    String name;
    int age;
    String sex;
    String school;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    @Override
    public String toString() {
        return ("姓名:"+name+"\n年龄:"+age+"\n性别"+sex+"\n学校"+school);
    }
}

 

2、写出这个类的映射接口,里面有我们要实现的查询的抽象方法。

package dao;

import bean.User;

public interface IUser {
    User getUserByID (int id);
}

 

3、写出这个类的映射Mapper文件,里面有select语句。

<?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">
<mapper namespace="dao.IUser">

    <select id="getUserByID" resultType="User" parameterType="int">
        SELECT * from user where id = #{id}
    </select>


</mapper>

 

4、以上都准备好之后,后面就是与没用spring不同的地方。

  • 准备mysql.properteis的参数配置文件,里面写上数据库连接要用到的参数。
  • jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8
    jdbc.uid=root
    jdbc.password=123456

     

  • mybatis文件与之前不同,之前实在mybatis-config.xml中配置数据库连接的,现在要把这些放在spring的配置文件中,所以mybatis配置文件中只写类的别名和引用的Mapper

  • <?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>
            <typeAlias alias="User" type="bean.User"/>
        </typeAliases>
    
        <!--<environments default="development">-->
            <!--<environment id="development">-->
                <!--<transactionManager type="JDBC"/>-->
                <!--<dataSource type="POOLED">-->
                    <!--<property name="driver" value="com.mysql.jdbc.Driver"/>-->
                    <!--<property name="url" value="jdbc:mysql://127.0.0.1/test?useUnicode=true&amp;characterEncoding=UTF-8"/>-->
                    <!--<property name="username" value="root"/>-->
                    <!--<property name="password" value="123456"/>-->
                <!--</dataSource>-->
            <!--</environment>-->
        <!--</environments>-->
    
    
        <mappers>
            <!-- // power by http://www.yiibai.com -->
            <mapper resource="xml/User.xml"/>
        </mappers>
    
    
    
    </configuration>

     

  • spring-config.xml中,我们要配置数据库连接池,和sqlSessionFactory对象,以及UserMapper对象。

    • sqlSessionFactory中引用mybatis-config.xml文件

    • userMapper中标明要实现的接口

<?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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">



<!--表明引用的参数配置文件是mysql-local.properties-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>
                mysql-local.properties
            </value>
        </list>
    </property>
</bean>


    <!--数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.uid}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 初始连接池大小 -->
        <property name="initialPoolSize" value="10"/>
        <!-- 连接池中连接最小个数 -->
        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="20"/>
     </bean>


    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="mybatis-spring-config.xml"/>

    </bean>

    <!--<bean id="sqlsessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">-->
        <!--<constructor-arg index="0" ref="sqlSessionFactory" />-->
    <!--</bean>-->

    <!--配置userMapper对象-->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="dao.IUser"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

 

5、以上3个xml文件都配置完成之后,我们调用这个查询方法就只需要短短几行代码。

package bean;

import dao.IUser;
import org.apache.ibatis.session.SqlSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        IUser userMapper = (IUser)context.getBean("userMapper");
        User user = userMapper.getUserByID(2);
        System.out.println(user);

    }

}

 

6、运行结果

Spring整合mybatis完整示例

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/131165.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 计算机三级网络技术大题暴力做题法

    计算机三级网络技术大题暴力做题法

    2021年9月28日
    56
  • php7使用curl扩展「建议收藏」

    php7使用curl扩展「建议收藏」  前言:最近项目中要调用一些接口,看到网上很多都使用curl,但由于刚开始,php很多的语法都不是很熟悉,例如如何调用第三方函数等,为了使用curl_init()等函数,从安装php的扩展curl开始踩了很多坑,对于环境安装真的是比较头疼的事情,往往可能因为一些小问题而不成功,而且按照网上乱七八糟的博客说的做,真的一点用都没有,特此记录一下,希望以后的编程生涯中尽量少犯这种错误。首先给出环境…

    2022年10月21日
    1
  • python抢淘宝的东西-Python 实现毫秒级淘宝抢购脚本的示例代码

    python抢淘宝的东西-Python 实现毫秒级淘宝抢购脚本的示例代码本篇文章主要介绍了Python通过selenium实现毫秒级自动抢购的示例代码,通过扫码登录即可自动完成一系列操作,抢购时间精确至毫秒,可抢加购物车等待时间结算的,也可以抢聚划算的商品。博主不提供任何服务器端程序,也不提供任何收费抢购软件。该文章仅作为学习selenium框架的一个示例代码。该思路可运用到其他任何网站,京东,天猫,淘宝均可使用,且不属于外挂或者软件之类,只属于一个自动化点击工具,…

    2022年6月10日
    42
  • Vue菜鸟教程

    Vue框架快速入门1.Vue的认识1.1什么是Vue?Vue是一个开源的javascript框架,并且Vue支持mvc和mvvm两种模式。Vue是一个构建数据驱动的web界面的渐进式框架。采用自底向上增量开发的设计。Vue.js的目标是通过尽可能简单的API实现响应的数据绑定和组合的视图组件,是又一个js库。MVC:Model(模型),View(视图),Controller(…

    2022年4月9日
    10.1K
  • ios—-protocol, optional ,delegate

    ios—-protocol, optional ,delegate

    2021年7月10日
    53
  • springbean生命周期通俗一点_spring为啥是单例模式

    springbean生命周期通俗一点_spring为啥是单例模式一、Spring核心模块介绍1.SpringCore:Core封装包是框架的最基础部分,提供IOC和依赖注入特性。这里的基础概念是BeanFactory,它提供对Factory模式的经典实现来消除对程序性单例模式的需要,并真正地允许你从程序逻辑中分离出依赖关系和配置。2.SpringContext:构建于Core封装包基础上的Context封装包,提供了一种框架式的对象访问方法,有些象JNDI注册器。Context封装包的特性得自于Beans封装包,并添加了对国际化(I18N).

    2022年9月18日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号