Java笔记之Mybatis(一):简单入门

1.新建数据库keeper

create database keeper

2.创建表t_student

USE keeper;
DROP
TABLE IF EXISTS `t_student`; CREATE TABLE `t_student` ( `student_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生ID', `student_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '学生姓名', `student_age` int(11) NULL DEFAULT NULL COMMENT '学生年龄', PRIMARY KEY (`student_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

3.导入学生数据

USE keeper;
INSERT INTO `t_student` VALUES (null, '张三', 23);
INSERT INTO `t_student` VALUES (null, '李四', 24);
INSERT INTO `t_student` VALUES (null, '王五', 25);
INSERT INTO `t_student` VALUES (null, '赵六', 26);
INSERT INTO `t_student` VALUES (null, '韩七', 27);

4.使用eclipse新建Java Project

5.创建文件夹lib,导入jar包,并Build Path

6.在包com.mybatis.demo.pojo下新建Student类

package com.mybatis.demo.pojo;

public class Student {
    private int studentId;
    private String studentName;
    private int studentAge;
    public int getStudentId() {
        return studentId;
    }
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public int getStudentAge() {
        return studentAge;
    }
    public void setStudentAge(int studentAge) {
        this.studentAge = studentAge;
    }
    
    
}

7.在包com.mybatis.demo.pojo下新建Student.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.mybatis.demo.pojo">
    <select id="getAllStudent" resultType="Student">
        select 
            student_id studentId,
            student_name studentName,
            student_age studentAge 
        from 
            t_student
    </select>
</mapper>

8.在src目录下新建mybatisConfig.xml

扫描二维码关注公众号,回复: 10149733 查看本文章
<?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>
        <!-- 类的别名默认为类名 -->
        <package name="com.mybatis.demo.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 定义数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/keeper?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置sql映射配置文件 -->
    <mappers>
        <mapper resource="com/mybatis/demo/pojo/Student.xml"/>
    </mappers>
</configuration>

9.在包com.mybatis.demo.test下新建MybatisTest类

package com.mybatis.demo.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

import com.mybatis.demo.pojo.Student;

public class MybatisTest {

    public static void main(String[] args) throws IOException {
        //加载mybatis的配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
        //获取SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //使用SqlSessionFactory对象创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //查询结果为多条,使用selectList方法,如果结果为一条,使用selectOne方法
        List<Student> students = sqlSession.selectList("getAllStudent");
        //遍历打印学生信息
        for (Student student : students) {
            System.out.println(student.getStudentId()+"\t"+
                    student.getStudentName()+"\t"+student.getStudentAge());
        }
    }

}

10.运行MybatisTest类,查看结果

11.说明

  (1)包名自定义,只需要把mybatisConfig.xml中关于类别名和sql映射配置文件的部分改成自己的包名结构,Student.xml中的命名空间改成自己的包名即可;

  (2)数据库连接信息填写自己的;

  (3)Student.xml中的查询结果字段名要与Student类的属性名保持一致,也可以改成如下配置:

  其中,mybatisConfig.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>
    <settings>
        <!-- 开启驼峰命名规则映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 对类起别名 -->
    <typeAliases>
        <!-- 类的别名默认为类名 -->
        <package name="com.mybatis.demo.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 定义数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/keeper?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置sql映射配置文件 -->
    <mappers>
        <mapper resource="com/mybatis/demo/pojo/Student.xml"/>
    </mappers>
</configuration>

Student.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.mybatis.demo.pojo">
    <select id="getAllStudent" resultType="Student">
        select 
            student_id,
            student_name,
            student_age
        from 
            t_student
    </select>
</mapper>

重新运行MybatisTest类结果也是一样的.

猜你喜欢

转载自www.cnblogs.com/antusheng/p/12565098.html
今日推荐