Use MyBatis Based on XML, and use MyBatis for XML

Source: Internet
Author: User

Use MyBatis Based on XML, and use MyBatis for XML

1. Project Structure




2. entity Student
package net.hw.bean;

/**
 * Created by howard on 2016/4/25.
 */
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) {
        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 "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", branch='" + branch + '\'' +
                ", percentage=" + percentage +
                ", phone=" + phone +
                ", email='" + email + '\'' +
                '}';
    }
}
3. MyBatis configuration file SqlMapConfig
<? 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 = "net.hw.bean.Student" />
    </ typeAliases>

    <environments default = "development">
        <environment id = "development">
            <!-Type of transaction manager: JDBC, MANAGED->
            <transactionManager type = "JDBC" />
            <!-Type of data source: UNPOOLED, POOLED, JNDI->
            <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="root"/>
            </ dataSource>
        </ environment>
    </ environments>

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

</ configuration>
4. entity ing file StudentMapper. 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="Student">

    <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>

    <insert id="insert" parameterType="Student">
        INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )
        VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});
        <selectKey keyProperty = "id" resultType = "int" order = "AFTER">
            select last_insert_id() as id
        </selectKey>
    </insert>

    <update id="update" parameterType="Student">
        UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE =  #{phone} WHERE ID = #{id};
    </update>

    <delete id="deleteById" parameterType="int">
        DELETE from STUDENT WHERE ID = #{id};
    </delete>

    <select id="getAll" resultMap="result">
        SELECT * FROM STUDENT;
    </select>

    <select id="getById" parameterType="int" resultMap="result">
        SELECT * FROM STUDENT WHERE ID = #{id};
    </select>

</mapper>
5. StudentDao
package net.hw.dao;
import net.hw.bean.Student;
import java.util.List;
/**
 * Created by howard on 2016/4/25.
 */
public interface StudentDao {
    void insert(Student student);
    void update(Student student);
    void deleteById(int id);
    Student getById(int id);
    List<Student> getAll();
}

6. StudentDaoImpl

package net.hw.dao.impl;

import net.hw.bean.Student;
import net.hw.dao.StudentDao;
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 org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

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

/**
 * Created by howard on 2016/4/25.
 */
public class StudentDaoImpl implements StudentDao {

private SqlSessionFactory sqlSessionFactory;

public StudentDaoImpl() {
    try {
            Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void insert(Student student) {
        SqlSession session = sqlSessionFactory.openSession();
        session.insert("Student.insert", student);
        System.out.println("record inserted successfully");
        session.commit();
        session.close();
    }

    public void update(Student student) {
        SqlSession session = sqlSessionFactory.openSession();
        session.update("Student.update", student);
        System.out.println("record updated successfully");
        session.commit();
        session.close();
    }

    public void deleteById(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        session.delete("Student.deleteById", id);
        System.out.println("record deleted successfully");
        session.commit();
        session.close();
    }

    public Student getById(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        return session.selectOne("Student.getById", id);
    }

    public List<Student> getAll() {
        SqlSession session = sqlSessionFactory.openSession();
        return session.selectList("Student.getAll");
    }
}
7. Test Program StudentDaoImplTest
package net.hw.dao.impl;

import net.hw.bean.Student;
import net.hw.dao.StudentDao;
import org.junit.Test;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.List;

/**
 * Created by howard on 2016/4/25.
 */
public class StudentDaoImplTest {
    @Test
    public void testInsert() {
        Student student = new Student("Mohammad", "It", 80, 984803322, "Mohammad@gmail.com");
        StudentDao studentDao = new StudentDaoImpl();
        studentDao.insert(student);
    }

    @Test
    public void testUpdate() {
        StudentDao studentDao = new StudentDaoImpl();
        Student student = studentDao.getById(2);
        student.setEmail("Mohamma@163.com");
        studentDao.update(student);
    }

    @Test
    public void testDelete() {
        StudentDao studentDao = new StudentDaoImpl();
        studentDao.deleteById(2);
    }

    @Test
    public void testGetById() {
        StudentDao studentDao = new StudentDaoImpl();
        Student student = studentDao.getById(1);
        System.out.println(student);
    }

    @Test
    public void testGetAll() {
        StudentDao studentDao = new StudentDaoImpl();
        List<Student> students = studentDao.getAll();
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

Run the testInsert () method:


Run the testUpdate () method:


Run the testGetById () method:


Run the testGetAll () method:


Run the testDelete () method:


View comments



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.