其他分享
首页 > 其他分享> > mybatis安装和配置

mybatis安装和配置

作者:互联网

  本文并不限定你使用什么类型的 IDE(如 Eclipse,NetBeans IDE,或者 IntelliJ IDEA, 它们通过提供自动完成,重构,调试特性来很大程度上简化了开发)来编码,你可以选择你喜欢的 IDE。  
  本节将(通过以下步骤)说明如何使用 MyBatis 开发一个简单的 Java 项目: 新建表 STUDENTS,插入样本数据
  • 新建一个 Java 项目,将 MyBatis-3.2.2.jar 添加到 classpath 中
  • 新建建 MyBatisSqlSessionFactory 单例模式类
  • 新建映射器 StudentMapper 接口和 StudentService 类
  • 新建一个 JUnit 测试类来测试 StudentService

1.3.1 新建表 STUDENTS,插入样本数据 使用以下 SQL 脚本往 MySQL 数据库中创建 STUDENTS 表插入样本数据: SQL Code
 1 CREATE TABLE STUDENTS
 2 (
 3 stud_id int(11) NOT NULL AUTO_INCREMENT,
 4 name varchar(50) NOT NULL,
 5 email varchar(50) NOT NULL,
 6 dob date DEFAULT NULL,
 7 PRIMARY KEY (stud_id)
 8 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
 9 /*Sample Data for the students table */
10 insert into students(stud_id,name,email,dob)
11 values (1,'Student1','student1@gmail.com','1983-06-25');
12 insert into students(stud_id,name,email,dob)
13 values (2,'Student2','student2@gmail.com','1983-06-25');

 

 

1.3.2 新建一个 Java 项目,将 MyBatis-3.2.2.jar 添加到 classpath 中 v> 让我们创建一个 Java 项目,并被指 MyBatis JAR 包依赖:
XML Code
<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>

 

9.新建 log4j.properties 文件,添加到 classpath 中. NormalText Code
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n

 

1.3.3 新建 mybatis-config.xml 和映射器 StudentMapper.xml 配置文件
让我们来创建 MyBatis 的主要配置文件 mybatis-config.xml,其中包括数据库连接信息,类型别名等等;然后创 建一个包含了映射的 SQL 语句的 StudentMapper.xml 文件。 1. 创建 MyBatis 的主要配置文件 mybatis-config.xml,其中包括数据库连接信息,类型别名等等,然后将其加 到 classpath 中;   XML Code
<?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>
        <typeAlias alias="Student" type="entity.Student" />
    </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" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/StudentMapper.xml" />
    </mappers>
</configuration>

 

2. 创建 SQL 映射器 XML 配置文件 StudentMapper.xml 并且将它放在 com.mybatis3.mappers 包中 XML Code
<?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="mappers.StudentMapper">
    <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>

上述的 StudentMapper,xml 文件包含的映射的 SQL 语句可以通过 ID 加上名空间调用。

 
1.3.4 新建 MyBatisSqlSessionFactory 单例类 新建 MyBatisSqlSessionFactory.java 类文件,实例化它,使其持有一个 SqlSessionFactory 单例对象: Java Code
package util;
import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

public class MyBatisSqlSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory()
    {
        if(sqlSessionFactory == null)
            {
            InputStream inputStream;
            try
            {
                inputStream = Resources.
                getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new
                SqlSessionFactoryBuilder().build(inputStream);
                }
            catch (IOException e)
            {
                throw new RuntimeException(e.getCause());

            }

            }
        return sqlSessionFactory;
    }
    public static SqlSession openSession()
    {
        return getSqlSessionFactory().openSession();
    }
}
上述的代码段中,我们创建了一个 SqlSessionFactory 对象,我们将使用它来获得 SqlSession 对象和执行映射的 SQL 语句。
1.3.5 新建 StudentMapper 接口和 StudentService 类 让我们创建一个 StudentMapper 接口,其定义的方法名和在 Mapper XML 配置文件定义的 SQL 映射语句名称相同; 在创建一个 StudentService.java 类,包含了一些业务操作的实现。 1. 首先, 创建 JavaBean Student.java Java Code
package com.mybatis3.domain;
import java.util.Date;
public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob;
// setters and getters
}

 

2. 创建映射器 Mapper 接口 StudentMapper.java 其方法签名和 StudentMapper.xml 中定义的 SQL 映射定义名 相同 Java Code
package mappers;
import java.util.List;
import entity.Student;

public interface StudentMapper {
    List<Student> findAllStudents();
    Student findStudentById(Integer id);
    void insertStudent(Student student);
}

 

3. 现在创建 StudentService.java 实现对表 STUDENTS 的数据库操作 Java Code
package services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import entity.Student;
import mappers.StudentMapper;
import util.MyBatisSqlSessionFactory;

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 void createStudent(Student student)
    {
        SqlSession sqlSession =
                MyBatisSqlSessionFactory.openSession();
        try
        {
            StudentMapper studentMapper =
                    sqlSession.getMapper(StudentMapper.class);
            studentMapper.insertStudent(student);
            sqlSession.commit();
        }
        finally
        {
            sqlSession.close();
        }
    }
}

 

1.3.6 新建一个 JUnit 测试类来测试 StudentService27 新建一个 JUnit 测试类测试 StudentSerivce.java 中定义的方法。 Java Code
import java.util.*;
import org.junit.*;
import entity.Student;
import services.StudentService;

public class StudentTest {
    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();
        int id = 3;
        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);
        Assert.assertNotNull(newStudent);
        }
    }

 

 

标签:配置,Student,StudentMapper,student,mybatis,import,安装,public
来源: https://www.cnblogs.com/yangf428/p/12257613.html