MyBatis 教程01

1. 增删改查
2. 关系映射: 一对一, 一对多
<!--
\src\com\java1234\mappers\AddressMapper.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.java1234.mappers.AddressMapper"> <resultMap type="Address" id="AddressResult"> <result property="id" column="id"/> <result property="sheng" column="sheng"/> <result property="shi" column="shi"/> <result property="qu" column="qu"/> </resultMap> <select id="findById" parameterType="Integer" resultType="Address"> select * from t_address where id=#{id} </select> </mapper> <!-- \src\com\java1234\mappers\GradeMapper.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.java1234.mappers.GradeMapper"> <resultMap type="Grade" id="GradeResult"> <result property="id" column="id"/> <result property="gradeName" column="gradeName"/> <collection property="students" column="id" select="com.java1234.mappers.StudentMapper.findByGradeId"></collection> </resultMap> <select id="findById" parameterType="Integer" resultMap="GradeResult"> select * from t_grade where id=#{id} </select> </mapper> <!-- \src\com\java1234\mappers\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="com.java1234.mappers.StudentMapper"> <!-- <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <result property="address.id" column="addressId"/> <result property="address.sheng" column="sheng"/> <result property="address.shi" column="shi"/> <result property="address.qu" column="qu"/> </resultMap> --> <!-- <resultMap type="Address" id="AddressResult"> <result property="id" column="id"/> <result property="sheng" column="sheng"/> <result property="shi" column="shi"/> <result property="qu" column="qu"/> </resultMap> <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" resultMap="AddressResult"/> </resultMap> --> <!-- <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" javaType="Address"> <result property="id" column="id"/> <result property="sheng" column="sheng"/> <result property="shi" column="shi"/> <result property="qu" column="qu"/> </association> </resultMap> --> <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" column="addressId" select="com.java1234.mappers.AddressMapper.findById"></association> <association property="grade" column="gradeId" select="com.java1234.mappers.GradeMapper.findById"></association> </resultMap> <select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer"> select * from t_student t1,t_address t2 where t1.addressId=t2.id and t1.id=#{id} </select> <select id="findByGradeId" resultMap="StudentResult" parameterType="Integer"> select * from t_student where gradeId=#{gradeId} </select> <insert id="add" parameterType="Student" > insert into t_student values(null,#{name},#{age}) </insert> <update id="update" parameterType="Student"> update t_student set name=#{name},age=#{age} where id=#{id} </update> <delete id="delete" parameterType="Integer"> delete from t_student where id=#{id} </delete> <select id="findById" parameterType="Integer" resultType="Student"> select * from t_student where id=#{id} </select> <select id="find" resultMap="StudentResult"> select * from t_student </select> </mapper> <!-- \src\mybatis-config.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> <!-- <properties resource="jdbc.properties"/> --> <properties> <property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/> <property name="jdbc.url" value="jdbc:mysql://localhost:3306/db_mybatis"/> <property name="jdbc.username" value="root"/> <property name="jdbc.password" value="123456"/> </properties> <!-- <typeAliases> <typeAlias alias="Student" type="com.java1234.model.Student"/> </typeAliases> --> <typeAliases> <package name="com.java1234.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <!-- <mapper resource="com/java1234/mappers/StudentMapper.xml" /> --> <!-- <mapper class="com.java1234.mappers.StudentMapper"/> --> <package name="com.java1234.mappers"/> </mappers> </configuration>
# \src\jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456

# \src\log4j.properties
log4j.rootLogger=info,appender1,appender2

log4j.appender.appender1=org.apache.log4j.ConsoleAppender 

log4j.appender.appender2=org.apache.log4j.FileAppender 
log4j.appender.appender2.File=C:/logFile.txt
 
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  
// \src\com\java1234\mappers\AddressMapper.java
package com.java1234.mappers;

import com.java1234.model.Address;

public interface AddressMapper {

    public Address findById(Integer id);

}

// \src\com\java1234\mappers\GradeMapper.java
package com.java1234.mappers;

import com.java1234.model.Grade;

public interface GradeMapper {

    public Grade findById(Integer id);

}

// \src\com\java1234\mappers\StudentMapper.java
package com.java1234.mappers;

import java.util.List;

import com.java1234.model.Student;

public interface StudentMapper {

    public int add(Student student);
    
    public int update(Student student);
    
    public int delete(Integer id);
    
    public Student findById(Integer id);
    
    public List<Student> find();
    
    public Student findStudentWithAddress(Integer id);
    
    public Student findByGradeId(Integer gradeId);
}

// \src\com\java1234\model\Address.java
package com.java1234.model;

public class Address {

    private Integer id;
    private String sheng;
    private String shi;
    private String qu;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getSheng() {
        return sheng;
    }
    public void setSheng(String sheng) {
        this.sheng = sheng;
    }
    public String getShi() {
        return shi;
    }
    public void setShi(String shi) {
        this.shi = shi;
    }
    public String getQu() {
        return qu;
    }
    public void setQu(String qu) {
        this.qu = qu;
    }
    @Override
    public String toString() {
        return "Address [id=" + id + ", sheng=" + sheng + ", shi=" + shi
                + ", qu=" + qu + "]";
    }
    
    
}

// \src\com\java1234\model\Grade.java
package com.java1234.model;

import java.util.List;

public class Grade {

    private Integer id;
    private String gradeName;
    private List<Student> students;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getGradeName() {
        return gradeName;
    }
    public void setGradeName(String gradeName) {
        this.gradeName = gradeName;
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
    @Override
    public String toString() {
        return "Grade [id=" + id + ", gradeName=" + gradeName +"]";
    }
    
    
}

// \src\com\java1234\model\Student.java
package com.java1234.model;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private Address address;
    private Grade grade;
    
    
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    
    
    
    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }




    public Student(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }



    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 Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }


    public void setAddress(Address address) {
        this.address = address;
    }

    
    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }




    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", address=" + address + ", grade=" + grade + "]";
    }



    


    
    
    
}

// \src\com\java1234\service\GradeTest.java
package com.java1234.service;


import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.GradeMapper;
import com.java1234.model.Grade;
import com.java1234.util.SqlSessionFactoryUtil;

public class GradeTest {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession=null;
    private GradeMapper gradeMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        gradeMapper=sqlSession.getMapper(GradeMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testFindGradeWithStudents() {
        logger.info("查询年级(带学生)");
        Grade grade=gradeMapper.findById(1);
        System.out.println(grade);
    }
    
}

// \src\com\java1234\service\StudentTest.java
package com.java1234.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    
    public static void main(String[] args) {
        SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
        Student student=new Student("李四",11);
        int result=studentMapper.add(student);
        sqlSession.commit();
        if(result>0){
            logger.info("添加成功!");
        }
    }
}

// \src\com\java1234\service\StudentTest2.java
package com.java1234.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest2 {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testAdd() {
        logger.info("添加学生");
        Student student=new Student("王五",12);
        studentMapper.add(student);
        sqlSession.commit();
    }
    
    @Test
    public void testUpdate(){
        logger.info("修改学生");
        Student student=new Student(8,"王五2",13);
        studentMapper.update(student);
        sqlSession.commit();
    }
    
    @Test
    public void testDelete(){
        logger.info("删除学生");
        studentMapper.delete(8);
        sqlSession.commit();
    }
    
    @Test
    public void testFindById(){
        logger.info("通过ID查找学生");
        Student student=studentMapper.findById(1);
        System.out.println(student);
    }

    @Test
    public void testFind(){
        logger.info("查找所有学生");
        List<Student> studentList=studentMapper.find();
        for(Student s:studentList){
            System.out.println(s);
        }
    }
}

// \src\com\java1234\service\StudentTest3.java
package com.java1234.service;


import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest3 {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testFindStudentWithAddress() {
        logger.info("查询学生(带地址)");
        Student student=studentMapper.findStudentWithAddress(3);
        System.out.println(student);
    }
    
    @Test
    public void testFindStudentWithGrade(){
        logger.info("查询学生(带年级)");
        Student student=studentMapper.findStudentWithAddress(1);
        System.out.println(student);
    }
    
}

// \src\com\java1234\util\SqlSessionFactoryUtil.java
package com.java1234.util;

import java.io.InputStream;

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

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory;
    
    public static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory==null){
            InputStream inputStream=null;
            try{
                inputStream=Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
    
    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }
}

 

posted on 2017-09-04 23:00  程序员修仙之路  阅读(182)  评论(0编辑  收藏  举报