VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • Python
  • PHP
  • Eclipse
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Phần mềm tiện ích
    • Cấu trúc dữ liệu và giải thuật
    • Học lập trình C#
    • Selenium Test

MyBatis Tuts

MyBatis - MyBatis là gì? MyBatis - file cấu hình XML MyBatis - file mapper xml MyBatis - Annotations MyBatis - Stored Procedures MyBatis - Dynamic SQL MyBatis - Hibernate

MyBatis Examples

Tạo MyBatis project trong eclipse MyBatis Example - mapper bằng file XML MyBatis Example - mapper bằng các Annotation MyBatis Example - mapper bằng file XML + interface MyBatis Example - MyBatis + Spring

Mybatis - Stored Procedures


MyBatis là gì?
Cấu hình XML

Nội dung chính

  • Mybatis - Stored Procedures
  • Lớp Student POJO
  • File Config Mybatis SqlMapConfig.xml
  • Interface StudentMapper.java
  • Student.xml
  • File CallByIdTest.java

Mybatis - Stored Procedures

Bạn có thể gọi một stored procedure trong MyBatis, đầu tiên chúng ta phải tạo stored procedure trong MySQL.

Tạo bảng Student trong MySQL bằng câu lệnh sau:

CREATE TABLE details.student(
   ID int(10) NOT NULL AUTO_INCREMENT,
   NAME varchar(100) NOT NULL,
   BRANCH varchar(255) NOT NULL,
   PERCENTAGE int(3) NOT NULL,
   PHONE int(11) NOT NULL,
   EMAIL varchar(255) NOT NULL,
   PRIMARY KEY (`ID`)
);

Tạo stored procedure như sau trong MySQL

DELIMITER //
   DROP PROCEDURE IF EXISTS details.read_recordById //
   CREATE PROCEDURE details.read_recordById (IN student_id INT)
 
   BEGIN 
      SELECT * FROM STUDENT WHERE ID = student_id; 
   END// 
 
DELIMITER ;

Lớp Student POJO

package mybatis.mapper.entity;

public class Student {
    private int id;
    private String name;
    private String branch;
    private int percentage;
    private int phone;
    private String email;

    public Student() {
    }

    public Student(String name, String branch, int percentage, int phone, String email) {
        super();
        this.name = name;
        this.branch = branch;
        this.percentage = percentage;
        this.phone = phone;
        this.email = email;
    }

    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 String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public int getPercentage() {
        return percentage;
    }

    public void setPercentage(int percentage) {
        this.percentage = percentage;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return getClass().getName() + "[" + "id = " + id + ", name = " + name + ", branch = " + branch 
                + ", percentage = " + percentage  + ", phone = " + phone  + ", email = " + email + "]"; 
    }
}

File Config Mybatis SqlMapConfig.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>
    <typeAliases>
        <typeAlias alias="Student" type="mybatis.mapper.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/details" />
                <property name="username" value="root" />
                <property name="password" value="1234567890" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mybatis/mapper/sql/Student.xml" />
    </mappers>
</configuration>

Interface StudentMapper.java

package mybatis.mapper;

import mybatis.mapper.entity.Student;

public interface StudentMapper {
    Student readRecordById(int id);
}

Student.xml

Để ánh xạ với kết quả trả về của các thủ tục, chúng ta cần phải tạo một resultmap có kiểu alias là Student (mybatis.mapper.entity.Student). Để gọi thủ tục read_recordById, chúng ta cần định nghĩa thẻ select có id là callById.

<?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="mybatis.mapper.StudentMapper">

    <resultMap id="result" type="Student">
        <result property="id" column="ID" />
        <result property="name" column="NAME" />
        <result property="branch" column="BRANCH" />
        <result property="percentage" column="PERCENTAGE" />
        <result property="phone" column="PHONE" />
        <result property="email" column="EMAIL" />
    </resultMap>

    <select id="readRecordById" resultMap="result" parameterType="int" statementType="CALLABLE">
        {call read_recordById(#{id, jdbcType = INTEGER, mode = IN})}
    </select>

</mapper>

File CallByIdTest.java

File này xử lý các logic để độc thông tin của Student từ bẳng Student trong cơ sở dữ liệu.

public class CallByIdTest {
    public static void main(String[] args) throws IOException {
        Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sqlSessionFactory.openSession();

        // get student by Id
        Student student = session.selectOne("Student.readRecordById", 12);
        System.out.println(student);

        // close session
        session.close();
    }
}

Dowload Source Code

Download Now!

MyBatis là gì?
Cấu hình XML

Recent Updates

MyBatis là gì?MyBatis - AnnotationsMyBatis - Dynamic SQLMyBatis - file cấu hình XMLMybatis - File Mapper XMLMybatis - Stored ProceduresMyBatis Example - mapper bằng AnnotationsMyBatis Example - mapper bằng file XMLMyBatis Example - mapper bằng file XML và InterfaceMyBatis Example - MyBatis + SpringSự khác nhau giữa MyBatis và HibernateTạo MyBatis project trong eclipse

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn

Danh sách bài học

Học java
Học servlet
Học jsp
Học Hibernate
Học Struts2
Học Spring
Học SQL

Câu hỏi phỏng vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

About VietTuts.Vn

Hệ thống bài học trên VietTuts.Vn bao gồm các bài lý thuyết và thực hành về các công nghệ java và công nghệ web. Các bài lý thuyết trên hệ thống VietTuts.Vn được tham khảo và tổng hợp từ các trang http://javatpoint.com, http://www.tutorialspoint.com, http://docs.oracle.com/en …

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | VietTuts.Vn team | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml