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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 电平转换的作用_电平转换电路原理

    电平转换的作用_电平转换电路原理作为一名电子设计的硬件工程师,电平转换是每个人都必须面对的的话题,主芯片引脚使用的1.2V、1.8V、3.3V等,连接外部接口芯片使用的1.8V、3.3V、5V等,由于电平不匹配就必须进行电平转换。每个工程师都有自己的一套转换方案,今天我们将5种电平转换的方法进行汇总,并且总结各种的优劣势,避免设计过程踩坑。一、电平转换方法5种电平转换方法分别是:晶体管电平转换方法;专用电平转换芯片;限流电阻电平转换方法;电阻分压电平转换方法;二极管电平转换方法;下面我们会从速率、驱动能力、漏电流、成本

    2022年8月10日
    10
  • Eureka集群环境搭建

    Eureka集群环境搭建前言:Eureka已经停止更新了,在新的项目中,不推荐使用,通过对周阳老师视频的学习,本篇文章主要是简单介绍下Eureka,以及如何搭建集群环境的Eureka,让大家对Eureka有个初步的了解。1.什么是EurekaEureka是Netflix开发的,一个基于REST服务的,服务注册与发现的组件,以实现中间层服务器的负载平衡和故障转移。它主要包括两个组件:EurekaServer和EurekaClientEurekaClient:一个Java

    2022年6月1日
    43
  • Python之xpath

    xpath表达式格式xpath通过"路径表达式"来选择节点,在表现形式上与传统的文件系统类似绝对路径(absolutepath)必须用"/"起首,后面紧跟

    2021年12月18日
    52
  • 利用 SSDP 协议生成 100 Gbps DDoS 流量的真相探秘「建议收藏」

    利用 SSDP 协议生成 100 Gbps DDoS 流量的真相探秘「建议收藏」原文地址https://www.4hou.com/technology/5979.html上个月我们分享过一些反射型DDoS攻击数据,SSDP攻击的平均大小是12Gbps,我们记录的最大的反射式DDoS攻击是:1.30Mpps(每秒数百万个数据包)2.80Gbps(每秒数十亿位)3.使用940k反射器的IP几天前,我们注意到了一个不寻常的SSDP超级放大情况的发生…

    2022年10月10日
    3
  • 一个诡异的 JedisConnectionException: Connection refused 问题

    点击上方☝Java编程技术乐园,轻松关注!及时获取有趣有料的技术文章做一个积极的人编码、改bug、提升自己我有一个乐园,面向编程,春暖花开!出现问题我遇到的一个问题,在连接redis的时…

    2022年2月28日
    46
  • SQL 语句练习

    实验名称SQL语句练习实验地点实验楼502实验日期3.21 一、实验目的及要求 1.加深对表间关系的理解 2.理解数据库中数据的查询方法和应用 3.掌握各种查询的异同及相互之间的转换方法 4.掌握各种查询要求的实现 二、实验环境 Sql…

    2022年4月8日
    48

发表回复

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

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