spring mybatis工作环境搭建和测试示例

68 篇文章 0 订阅
40 篇文章 0 订阅

使用MyBatis框架,就要搭建它的工作环境,搭建MyBatis工作环境需要五个步骤,具体介绍如下。

 项目情况截图

 

新建项目并导入jar包

新建Maven项目,然后导入MyBatis和MySQL的jar包,在pom.xml导入依赖

总pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.shrimpking</groupId>
    <artifactId>springtest09</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>spring-01</module>
        <module>spring-02</module>
        <module>spring-03-bankapp</module>
        <module>spring-04</module>
        <module>spring-05-annotaion</module>
        <module>spring-06-mvc</module>
        <module>spring-07-b</module>
        <module>startmvc</module>
        <module>springmvc-01</module>
        <module>spingmvc-02-test</module>
        <module>springmvc-02-test</module>
        <module>springmvc-03-test</module>
        <module>springmvc-04-mysql</module>
        <module>springmvc-05-exeception</module>
        <module>springmvc-06-interceptor</module>
        <module>springmybatis-01</module>
    </modules>

    <!--
        spring 4.0.0
        servlet 3.0.1
        jsp-api 2.2
        jstl 1.2
        standard 1.1.2
        junit 3.8.1
        commons-logging 1.1.3

     -->
    <properties>
        <spring.version>4.0.0.RELEASE</spring.version>
        <servlet.version>3.0.1</servlet.version>
        <jsp-api.version>2.2</jsp-api.version>
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <junit.version>3.8.1</junit.version>
        <commons-logging.version>1.1.3</commons-logging.version>
        <jdk.version>1.8</jdk.version>
        <maven.complier.plugin.version>2.3.2</maven.complier.plugin.version>
    </properties>

    <dependencies>
        <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-jdbc</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-expression</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-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--servelt-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <!--  test      -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <!-- jstl       -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.complier.plugin.version}</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

module的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springtest09</artifactId>
        <groupId>com.shrimpking</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmybatis-01</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

建立数据库将表和类进行映射

在数据库中建立学生信息表student(id,name,sex,age,address),对应的实体类是Student,代码如下:

create table w_student(
	id int not null auto_increment primary key,
	name varchar(50) not null,
	sex varchar(10) null,
	age int null,
	address varchar(100) null
)

insert into w_student values(null,'zhang','boy',20,'新华门');
insert into w_student values(null,'zhang2','boy',20,'新华门');
insert into w_student values(null,'zhang3','boy',20,'新华门');
insert into w_student values(null,'zhang4','boy',20,'新华门');

Student.java

package com.shrimpking.pojo;

/**
 * @author user1
 */
public class Student
{
    private long id;
    private String name;
    private String sex;
    private int age;
    private String address;

    public Student()
    {
    }

    public Student(long id, String name, String sex, int age, String address)
    {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.address = address;
    }

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getSex()
    {
        return sex;
    }

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

    public int getAge()
    {
        return age;
    }

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

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public String toString()
    {
        return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", address='" + address + '\'' + '}';
    }
}

配置文件连接数据库

在MyBatis的配置文件中,由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.shrimpking.pojo"/>
    </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://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimeZone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="mysql123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/shrimpking/dao/StudentMapper.xml"/>
    </mappers>
</configuration>

实现接口

接口即DAO层,主要在此层进行增、删、改、查。首先在src/main/java文件夹中建立com.shrimpking.pojo包,然后定义学生接口StudentDao,具体代码如下:

StudentDao.java

package com.shrimpking.dao;

import com.shrimpking.pojo.Student;

/**
 * @author user1
 */
public interface StudentDao
{
    /**
     * 查询
     * @param id
     * @return
     */
    public Student findStudentById(long id);

    /**
     * 增加
     * @param student
     */
    public void addStudent(Student student);

    /**
     * 修改
     * @param student
     */
    public void updateStudent(Student student);

    /**
     * 删除
     * @param id
     */
    public void deleteStudent(long id);
}

通过映射文件来实现接口,StudentDao接口映射文件StudentMapper.xml的代码如下:

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.shrimpking.dao.StudentDao">

    <!-- 查询   -->
    <select id="findStudentById" parameterType="long" resultType="Student">
        select * from w_student where id = #{id}
    </select>

    <!-- 增加   -->
    <insert id="addStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
        insert into w_student(name,sex,age,address) values(#{name},#{sex},#{age},#{address})
    </insert>

    <!-- 修改  -->
    <update id="updateStudent"  parameterType="Student">
        update w_student set
        name = #{name},
        sex = #{sex},
        age = #{age},
        address = #{address}
        where id = #{id}
    </update>

    <!-- 删除   -->
    <delete id="deleteStudent"  parameterType="long">
        delete from w_student where id = #{id}
    </delete>

</mapper>

测试是否搭建成功

下面测试MyBatis是否搭建成功,在src/test/java文件夹中新建包com.shrimpking.test,test包下新建测试类StudentTest,代码如下:

StudentTest.java

package com.shrimpking.test;

import com.shrimpking.dao.StudentDao;
import com.shrimpking.pojo.Student;
import com.shrimpking.utils.DaoUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.io.IOException;


public class StudentTest
{

    @Test
    public void test() throws IOException
    {
        SqlSession sqlSession = DaoUtils.getSqlSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = mapper.findStudentById(1L);
        System.out.println(student);
        student.setName("张三");
        student.setAddress("北京");
        mapper.updateStudent(student);
        sqlSession.commit();
    }
}

DaoUtils.java

package com.shrimpking.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author user1
 */
public class DaoUtils
{
    private static Reader reader;
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession() throws IOException
    {
        try
        {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            //
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            reader.close();
        }
        return sqlSessionFactory.openSession();
    }
}

运行截图

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值