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));
    }

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

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