当前位置:首页 > 开发 > 开源软件 > 正文

【持久化框架MyBatis3一】MyBatis版HelloWorld

发表于: 2014-09-06   作者:bit1129   来源:转载   浏览:
摘要: MyBatis这个系列的文章,主要参考《Java Persistence with MyBatis 3》。   样例数据 本文以MySQL数据库为例,建立一个STUDENTS表,插入两条数据,然后进行单表的增删改查     CREATE TABLE STUDENTS ( stud_id int(11) NOT NULL AUTO_INCREMENT,

MyBatis这个系列的文章,主要参考《Java Persistence with MyBatis 3》。

 

样例数据

本文以MySQL数据库为例,建立一个STUDENTS表,插入两条数据,然后进行单表的增删改查

 

 

CREATE TABLE STUDENTS
(
stud_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
dob date DEFAULT NULL,
PRIMARY KEY (stud_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=UTF-8;

/*Sample Data for the students table */
insert into students(stud_id,name,email,dob)
values (1,'Student1','student1@gmail.com','1983-06-25');
insert into students(stud_id,name,email,dob)
values (2,'Student2','student2@gmail.com','1983-06-25');

 

新建Maven项目,定义pom.xml

 MyBatis Maven项目依赖

 

 

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.22</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 

 

 

 

定义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>
    <properties resource="config.properties"><!--定义配置信息,在本配置中可以使用${key}来引用-->
       <!--同名的key,config.properties覆盖property子元素的属性值-->
        <property name="name1" value="value.in.property.element"/>
    </properties>
    <typeAliases>
        <!--类型的别名: 用法,在resultType和parameterType可以使用别名,而不是全限定的类名-->
        <typeAlias alias="Student" type="com.mybatis3.domain.Student"/>
        <!--包名下的Model类,使用类名作为别名,不区分大小写-->
        <package name="com.mybatis3.domain"/>
    </typeAliases>
    <environments default="development"><!--默认的环境信息,在生产环境中需要修改production-->
        <environment id="development"><!--开发环境的配置-->
            <!--事务管理,MyBatis提供了两种方式,JDBC的连接事务管理以及Managed-->
            <transactionManager type="JDBC"/>
            <!--数据源配置-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
        <environment id="production"><!--生产环境的配置-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--SQL映射文件,可以多个-->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
 

 

 

 

定义SQL映射配置文件Students-Mapper.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.mybatis3.mappers.StudentMapper"> <!--namespace定义的Mapper可以作为Mapper接口-->
    <!--SQL列与POJO的字段的映射关系-->
    <resultMap type="Student" id="StudentResult">
        <id property="studId" column="stud_id"/>
        <result property="name" column="name"/>
        <result property="email" column="email"/>
        <result property="dob" column="dob"/>
    </resultMap>
    <select id="findAllStudents" resultMap="StudentResult">
        SELECT * FROM STUDENTS
    </select>
    <select id="findStudentById" parameterType="int" resultType="Student">
        SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
        FROM STUDENTS WHERE STUD_ID=#{Id}
    </select>
    <insert id="insertStudent" parameterType="student">
        INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
        VALUES(#{studId },#{name},#{email},#{dob})
    </insert>
</mapper>
 

 

定义主配置文件使用的config.properties

 

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
key=value.in.config.properties

 

 

定义Model

 

package com.mybatis3.domain;

import java.util.Date;

public class Student {
    private Long studId;
    private String name;
    private String email;
    private Date dob;

    public Long getStudId() {
        return studId;
    }

    public void setStudId(Long studId) {
        this.studId = studId;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }
}

 

 

定义StudentMapper接口

 

package com.mybatis3.mappers;

import com.mybatis3.domain.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> findAllStudents();

    Student findStudentById(Integer id);

    void insertStudent(Student student);
}

 

定义StudentService

 

package com.mybatis3.serivces;

import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class StudentService {
    private Logger logger =
            LoggerFactory.getLogger(getClass());

    public List<Student> findAllStudents() {
        SqlSession sqlSession =
                MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper =
                    sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findAllStudents();
        } finally {
            //If sqlSession is not closed then database Connection associated this sqlSession will not be
            //returned to pool and application may run out of connections.
            sqlSession.close();
        }
    }

    public Student findStudentById(Integer studId) {
        logger.debug("Select Student By ID :{}", studId);
        SqlSession sqlSession =
                MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper =
                    sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findStudentById(studId);
        } finally {
            sqlSession.close();
        }
    }

    public Student findStudentById2(Integer studId) {
        logger.debug("Select Student By ID :{}", studId);
        SqlSession sqlSession =
                MyBatisSqlSessionFactory.openSession();
        try {
            Student student = (Student) sqlSession.
                    selectOne("com.mybatis3.mappers.StudentMapper.findStudentById",
                            studId);
            return student;
        } finally {
            sqlSession.close();
        }
    }

    public void createStudent(Student student) {
        SqlSession sqlSession =
                MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper =
                    sqlSession.getMapper(StudentMapper.class);
            studentMapper.insertStudent(student);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

 

 

单元测试

 

package com.mybatis3.services;

import com.mybatis3.domain.Student;
import com.mybatis3.serivces.StudentService;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Date;
import java.util.List;

public class StudentServiceTest {
    private static StudentService studentService;

    @BeforeClass
    public static void setup() {
        studentService = new StudentService();
    }

    @AfterClass
    public static void tearDown() {
        studentService = null;
    }

    @Test
    public void testFindAllStudents() {
        List<Student> students = studentService.findAllStudents();
        Assert.assertNotNull(students);
        for (Student student : students) {
            System.out.println(student);
        }
    }

    @Test
    public void testFindStudentById() {
        Student student = studentService.findStudentById(1);
        Assert.assertNotNull(student);
        System.out.println(student);
    }

    @Test
    public void testCreateStudent() {
        Student student = new Student();
        Long id = 1L;
        student.setStudId(id);
        student.setName("student_" + id);
        student.setEmail("student_" + id + "gmail.com");
        student.setDob(new Date());
        studentService.createStudent(student);
        Student newStudent = studentService.findStudentById(id.intValue());
        Assert.assertNotNull(newStudent);
    }


}

 

 

 

【持久化框架MyBatis3一】MyBatis版HelloWorld

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
MyBatis的主配置文件对MyBatis进行配置和定制,包括 全局属性定义(properties) MyBatis的行为设置(s
MyBatis的主配置文件对MyBatis进行配置和定制,包括 全局属性定义(properties) MyBatis的行为设置(s
MyBatis的主配置文件对MyBatis进行配置和定制,包括 全局属性定义(properties) MyBatis的行为设置(s
前言 这篇博文我们重点分析一下Mybatis与Hibernate的区别,当然在前面的博文中我们已经深入的研究了
从这篇博文开始我们学习一下Mybatis,希望大家提出宝贵的建议。 什么是Mybatis MyBatis 本是apache
前言 这篇博文我们重点分析一下Mybatis与Hibernate的区别,当然在前面的博文中我们已经深入的研究了
从这篇博文开始我们学习一下Mybatis,希望大家提出宝贵的建议。 什么是Mybatis MyBatis 本是apache
项目的目录结构: 一、添加mybatis.jar以及mysql的驱动包 二、创建数据的表 三、编写与表对应的实体
在不引用任何框架下,我们会通过平凡的代码不停的对数据库进行操作,产生了很多冗余的但是又有规律
什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号