创建第一个MyBatis实例(详细)


创建第一个MyBatis实例

(1),创建数据库中的表;
(2),创建项目并添加MyBatis框架所需的jar包;
(3),编写实体类;
(4),编写与实体类对应的映射接口(xxxMapper.java),以及映射配置文件(xxxMapper.xml);
(5),配置MyBatis框架的配置文件(mybatis-config.xml);
(6),编写MyBatis框架工具类;
(7),编写测试应用类并运行;

1,创建表: tb_student

create table TB_STUDENT
(
    id int not null,
   `name`VARCHAR(50) not null,
    score int not null,
    PRIMARY KEY(id)
);

2,创建项目

添加所需的jar包到/WEB-INF/lib

3,编写实体类

编写与tb_student表对应的实体类Student,代码如下

package com.mybatis.pojos;

public class Student {
    private int id;
    private String name;
    private int score;

    //必须要有无参的构造方法,不然根据StudentMapper.xml中的配置,在查询数据库时,将不能反射构造出Student实列
    public Student(){       
    }

    //带参数的构造方法
    public Student(int id,String name,int score){
        this.id=id;
        this.name=name;
        this.score=score;
    }

    @Override
    public String toString(){
        return "学号: "+id+"\n姓名: "+name+"\n成绩: "+score;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }           
}

4,关系映射

编写与Student实体类所对应的映射接口StudentMapper,该接口是用于数据访问操作的接口,代码如下

package com.mybatis.mapper;

import com.mybatis.pojos.Student;

public interface StudentMapper {
    public void insertStudent(Student student);//添加学生对象

    public Student getStudent(String name); //查找学生对象
}

编写对应的映射配置文件StudentMapper.xml,代码如下




<mapper namespace="com.mybatis.mapper.StudentMapper">

    <insert id="insertStudent" parameterType="Student">
        insert into tb_student(id,name,score)values(#{id},#{name},#{score})     
    insert>

    
    <select id="getStudent" resultType="Student"
        parameterType="java.lang.String" >
        select id,name,score from tb_student where name=#{name}
    select>

mapper>

5,配置mybatis-config.xml

代码如下



<configuration>
    <settings>
        <setting name="cacheEnabled" value="false" />
        <setting name="useGeneratedKeys" value="true" />
        <setting name="defaultExecutorType" value="REUSE" />    
    settings>

    <typeAliases>
        <typeAlias alias="Student" type="com.mybatis.pojos.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/hibernateuser" />
                <property name="username"   value="root" />
                <property name="password"   value="root" />         
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource = "com/mybatis/mapper/StudentMapper.xml">mapper>
    mappers>

configuration>

6,编写MyBatisUtil工具类

用于获取SqlSessionFactory对象,代码如下

package com.mybatis.util;

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

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

public class MyBatisUtil {
    private final static SqlSessionFactory sqlSessionFactory;

    static{
        String resource="mybatis-config.xml";
        Reader reader=null;
        try{
            //加载"mybatis-config.xml
            reader = Resources.getResourceAsReader(resource);
        }catch(IOException e){
            System.out.println(e.getMessage());
        }
        sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

7,编写测试应用类

package com.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.mybatis.mapper.StudentMapper;
import com.mybatis.pojos.Student;
import com.mybatis.util.MyBatisUtil;

public class MyBatisDemo {

    static SqlSessionFactory sqlSessionFactory=MyBatisUtil.getSqlSessionFactory();

    public static void main(String[] args) {        

//      //添加4个学生对象
//      addStudent(new Student(1,"it",89));
//      addStudent(new Student(2,"is",98));
//      addStudent(new Student(3,"so",99));
//      addStudent(new Student(4,"easy",99));

        //根据姓名查找
        Student student=getStudent("niu");
        System.out.println(student.toString());
    }

    //添加学生信息
    public static void addStudent(Student student){
        //打开SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            //获取Mapper对象
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            //插入操作
            studentMapper.insertStudent(student);
            //提交SqlSession
            sqlSession.commit();
            System.out.println("添加成功");
        }finally{
            //关闭sqlSession
            sqlSession.close();
        }
    }

    //根据姓名查找学生信息
    public static Student getStudent(String name){
        Student student=null;
        //打开SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            //获取Mapper对象
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            //查找操作
            student=studentMapper.getStudent(name);     
        }finally{
            //关闭sqlSession
            sqlSession.close();
        }
        return student;
    }
}

项目文件目录如下:
创建第一个MyBatis实例(详细)_第1张图片

你可能感兴趣的:(web,mybatis)