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

编程技术  /  houtizong 发布于 3年前   106

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','[email protected]','1983-06-25');insert into students(stud_id,name,email,dob)values (2,'Student2','[email protected]','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.Driverurl=jdbc:mysql://localhost:3306/testusername=rootpassword=rootkey=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);    }}

 

 

 

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客