Spring+MyBatis实例详解「建议收藏」

Spring+MyBatis实例详解「建议收藏」1.项目结构:                2.项目的Maven依赖:<properties> <spring-version>4.3.21.RELEASE</spring-version> </properties> <dependencies> <dependen…

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

1.项目结构:

                Spring+MyBatis实例详解「建议收藏」

2.项目的Maven依赖:

<properties>
        <spring-version>4.3.21.RELEASE</spring-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.Java类:
   3.1 Student.java

package com.lance.mybatis.demo.entity;

import lombok.Data;
import org.springframework.stereotype.Component;

@Component
@Data
public class Student {
    private String id;
    private String name;
    private byte age;
    private String sex;

}

3.2 StudentMapper.java

package com.lance.mybatis.demo.mapper;

import com.lance.mybatis.demo.entity.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface StudentMapper {

    void addStudent(Student s);

    void deleteStudentById(@Param("id") String id);

    int updateStudent(Student s);

    List<Student> findStudent(@Param("limit") int limit, @Param("offset") int offset);

    Student findById(@Param("id") String id);

    List<Student> findByIds(@Param("ids") List ids);
}

4.配置文件:

4.1 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>
  <settings>
    <setting name="cacheEnabled" value="false"/>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="multipleResultSetsEnabled" value="true"/>
    <setting name="useColumnLabel" value="true"/>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="autoMappingBehavior" value="PARTIAL"/>
    <setting name="defaultExecutorType" value="SIMPLE"/>
    <setting name="defaultStatementTimeout" value="25"/>
    <setting name="safeRowBoundsEnabled" value="false"/>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="localCacheScope" value="STATEMENT"/>
    <setting name="jdbcTypeForNull" value="OTHER"/>
    <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
  </settings>

  <mappers>
    <mapper resource="StudentMapper.xml"/>
  </mappers>

</configuration>

4.2 StudentMapper.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">
<mapper namespace="com.lance.mybatis.demo.mapper.StudentMapper">
    <update id="updateStudent" parameterType="com.lance.mybatis.demo.entity.Student">
        update student set name=#{name},age=#{age},sex=#{sex} where id=#{id}
    </update>

    <resultMap type="com.lance.mybatis.demo.entity.Student" id="students">
        <id column="id" property="id" jdbcType="CHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="TINYINT"/>
        <result column="sex" property="sex" jdbcType="CHAR"/>
    </resultMap>


    <select id="findStudent" resultMap="students">
        select * from student limit #{limit} offset #{offset}
    </select>

    <select id="findById" resultMap="students">
        select * from student where id = #{id}
    </select>

    <insert id="addStudent">
        insert into student(id,name,age,sex) VALUES (#{id},#{name},#{age},#{sex})
    </insert>

    <delete id="deleteStudentById">
        delete from student where id = #{id}
    </delete>

  <select id="findByIds" resultMap="students">
        select * from student where id in
        <foreach collection="ids" item="id" index="index" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

</mapper>

4.3 applicationContext.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"></property>
        <property name="url" value="jdbc:postgresql://***:5432/***"></property>
        <property name="username" value="***"></property>
        <property name="password" value="***"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.lance.mybatis.demo.mapper.StudentMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>


</beans>

5.单元测试
StudentMapperTest.java

package com.lance.mybatis.demo.mapper;


import com.alibaba.fastjson.JSON;
import com.lance.mybatis.demo.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class StudentMapperTest {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void getStudent() {
        List<Student> students = studentMapper.findStudent(2,1);
        System.out.println(JSON.toJSONString(students));
    }

    @Test
    public void addStudent() {
        Student student = new Student();
        student.setId("20181204");
        student.setName("wanger");
        student.setAge((byte) 20);
        student.setSex("男");

        studentMapper.addStudent(student);
    }

    @Test
    public void deleteStudentById() {

        studentMapper.deleteStudentById("20181201");

    }


    @Test
    public void findById() {

        Student student = studentMapper.findById("20181201");
        System.out.println(JSON.toJSONString(student));
    }

    @Test
    public void updateStudent() {
        Student student = new Student();
        student.setId("20181201");
        student.setName("xiaoming");
        student.setAge((byte) 20);
        student.setSex("男");

        studentMapper.updateStudent(student);
    }

   @Test
    public void findByIds() {
        List<String> ids = new ArrayList<String>();
        ids.add("20181203");
        ids.add("20181204");

        List<Student> students = studentMapper.findByIds(ids);
        System.out.println(JSON.toJSONString(students));
    }

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

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

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


相关推荐

  • 在线词云制作生成 tagxedo

    在线词云制作生成 tagxedo在线词云制作生成tagxedo在线词云10行Python代码的词云待办在线词云原博文地址和详细使用方法介绍在线词云制作tagxedo在线网址http://www.tagxedo.com/注意点:直接访问http://www.tagxedo.com/app.html可能会超时,先进主页再点击右上角的create按钮进入创作页面会加载更快;需要下载一个软件,使用IE浏览器可加载上述软件,谷歌和EDGE实测都无法加载;导出的词云图片:10行Python代码的词云原博客地址:1

    2025年7月21日
    0
  • java adminlte 使用_AdminLTE的使用

    java adminlte 使用_AdminLTE的使用第一次听说这个模板,留着以后用1.AdminLTE的必要配置文件2.自定义主题样式(1)在body中设置class。skin-blue:主题颜色,如果引入了_all-skins.min.css,有很多颜色可以选择,如左图,设置为skin-blue默认就为右图的主题样式。sidebar-mini:在AdminLTE.css中可以找到。(2)wrapper设置:AdminLTE…

    2022年7月27日
    3
  • GoogLeNet 神经网络结构

    GoogLeNet 神经网络结构GoogLeNet是2014年ILSVRC冠军模型,top-5错误率6.7%,GoogLeNet做了更大胆的网络上的尝试而不像vgg继承了lenet以及alexnet的一些框架,该模型虽然有22层,但参数量只有AlexNet的1/12。GoogLeNet论文指出获得高质量模型最保险的做法就是增加模型的深度(层数)或者是其宽度(层核或者神经元数),但是一般情况下更深或更宽的网络

    2022年8月14日
    8
  • javascript百炼成仙 第一章 掌握JavaScript基础 1.2直接量

    javascript百炼成仙 第一章 掌握JavaScript基础 1.2直接量叶小凡的住处被安排在青山院西北角的一个房间里,虽不宽敞,倒也干净。叶小凡两眼露出振奋的眼神,随便吃了点乡亲们准备的干粮后,就立刻开始打坐修行。编程之修,重在积累,而非资质。资质虽然一样重要,可是后天的努力一样必不可少。这些道理,叶小凡还未上山之前,就已经熟知!因此,即便是资质平凡,只要肯下苦功,一样可以修得正果!叶小凡虽然甲等资质,可依然不骄不躁,开始从“JavaScript基础修炼要诀”第一页开始看起。修炼要诀第一章,直接量。编程世界,所谓直接量,就是明面上可以见到的数据值。常见的直接量有数字,小数,

    2022年6月11日
    42
  • java Random.nextInt()方法

    java Random.nextInt()方法publicintnextInt(intn)该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。直接上代码:

    2022年7月4日
    26
  • visdom 使用教程

    visdom 使用教程visdom教程visdom安装与启动服务visdom常用功能image窗口:图像显示与更新窗口显示images窗口:多个图像显示与更新窗口显示text窗口:显示文本与更新文本line窗口:绘制折线图与更新折线图scatter窗口:绘制散点图与更新散点图visdom安装与启动服务安装visdompipinstallvisdom打开服务python-mvisdom.server…

    2022年6月24日
    29

发表回复

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

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