首页 > 代码库 > 最基础的mybatis入门demo

最基础的mybatis入门demo

demo结构

技术分享

数据库情况 (不会转sql语句 骚瑞)

技术分享技术分享

 

数据库连接信息 jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql_demo
jdbc.username=root
jdbc.password=root

javabean Student.class

package entity;

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private Integer tId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 Integer getAge() {
        return age;
    }

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

    public Integer gettId() {
        return tId;
    }

    public void settId(Integer tId) {
        this.tId = tId;
    }
}

mybatis配置 mybatis-cfg.xml

<?xml version="1.0" encoding="UTF-8" ?><!--xml版本声明-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--xml约束-->
<configuration> <!--Configuration配置;结构;外形-->

    <properties resource="resource/jdbc.properties"/> <!--加载配置文件->jdbc.properties 数据库文件-->

    <typeAliases><!--对象映射的位置-->
                <!--<typeAlias type="entity.Student"/>直接写n个对象-->
                <!--<package name="entity"/> 扫描包-->
        <package name="entity"/>
    </typeAliases>
    <environments default="mybatis-demo"><!--id随便写-->
        <environment id="mybatis-demo"><!--随便写-->
            <transactionManager type="JDBC"></transactionManager><!--事务管理器 目前是JDBC 以后交给Spring管理事务-->
            <dataSource type="POOLED"><!--数据源 POOLED相当于连接池 池里放链接 -->
                <property name="driver" value="${jdbc.driver}"/><!--${}用于读取上面jdbc.properties配置文件-->
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/><!--以上是通过反射原理注入-->

            </dataSource>
        </environment>
    </environments>
    <mappers><!--声明配置的mapper映射位置 可写文件 这里写的是包-->
        <package name="dao"/>
    </mappers>
</configuration>

定义查询接口StudentMapper.java

import java.util.List;

/**
 * Created by zekai on 2017/6/10.
 */
public interface StudentMapper {//该接口只定义查询方法 不执行具体查询
    //接口方法默认自带public
    int insertStudent(Student student) throws Exception;// 插入 int判断是否执行成功

    Student selectOneById(int id) throws Exception;//查询一条数据

    List<Student> selectAllStudent();//查询列表 封装到list中
}

 

映射文件 StudentMapper.xml (必须与StudentMapper同名)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.StudentMapper"><!--标志mapper(映射)是哪一个接口的mapper-->
    <resultMap id="studentMapper" type="entity.Student"><!--声明mapper的id type表示映射道德javabean-->
        <id column="Sid" property="id"/><!--id 主键 column?数据库 property?javabean 这里省略了java type等-->
        <result property="name" column="Sname"/>
        <result property="sex" column="Ssex"/>
        <result property="tId" column="Tid"/>
        <result property="age" column="SageNum"/>
    </resultMap>
    <insert id="insertStudent" parameterType="entity.Student" ><!--parameter表示传入参数是啥--><!--对应StudentMapper接口里的方法名-->

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum)VALUES (#{id},#{name},#{sex},#{tId},#{age})
<!--#{}对应studentmapper里的参数-->
    </insert>
    <select id="selectOneById" resultMap="studentMapper">
        SELECT * FROM student WHERE Sid=#{id}
    </select>
    <select id="selectAllStudent" resultMap="studentMapper"><!--resultType可设定返回类型-->
        SELECT *FROM student
    </select>
</mapper>

测试方法(debug)  Main.java

import dao.StudentMapper;
import entity.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;
//根据配置文件生成sqlsessionfactory
/**
 * Created by zekai on 2017/6/10.
 */
public class Main {
    public static void main(String[] args) throws Exception {
        //io加载配置文件
        InputStream in=Main.class.getResourceAsStream("resource/mybatis-cfg.xml");
        //用构建器构建一个inputstream
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session=factory.openSession();
       //取得mapper对象 调用mapper方法
        StudentMapper mapper=session.getMapper(StudentMapper.class);
        Student student=new Student();
//        student.setId(20);
//        student.setAge(28);
//        student.setName("alowang");
//        student.settId(2);
//        mapper.insertStudent(student);
       // student=mapper.selectOneById(2);
        List<Student> studentList=mapper.selectAllStudent();

        //记得提交 不提交等于啥都没干
        session.commit();
        //关闭资源
        session.close();
        }
    }

 

最基础的mybatis入门demo