基於XML使用MyBatis,XML使用MyBatis

來源:互聯網
上載者:User

基於XML使用MyBatis,XML使用MyBatis

1、項目結構圖



2、實體類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設定檔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">            <!--交易管理員的類型:JDBC, MANAGED-->            <transactionManager type="JDBC"/>            <!--資料來源的類型: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、實體對應檔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、測試程式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);        }    }}

執行testInsert()方法:


執行testUpdate()方法:


執行testGetById()方法:


執行testGetAll()方法:


執行testDelete()方法:


查看評論

相關文章

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.