MyBatis 教程03

Posted c0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis 教程03相关的知识,希望对你有一定的参考价值。

<!-- \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"/>
    <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>
        <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 org.apache.ibatis.annotations.Select;

import com.java1234.model.Address;

public interface AddressMapper {

    @Select("select * from t_address where id=#{id}")
    public Address findById(Integer id);

}

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

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.java1234.model.Grade;

public interface GradeMapper {

    @Select("select * from t_grade where id=#{id}")
    @Results(
            {
                @Result(id=true,column="id",property="id"),
                @Result(column="gradeName",property="gradeName"),
                @Result(column="id",property="students",[email protected](select="com.java1234.mappers.StudentMapper.selectStudentByGradeId"))
            }
    )
    public Grade findById(Integer id);

}

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

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.java1234.model.Student;


public interface StudentMapper {

    @Insert("insert into t_student values(null,#{name},#{age})")
    public int insertStudent(Student student);
    
    @Update("update t_student set name=#{name},age=#{age} where id=#{id}")
    public int updateStudent(Student student);
    
    @Delete("delete from t_student where id=#{id}")
    public int deleteStudent(int id);
    
    @Select("select * from t_student where id=#{id}")
    public Student getStudentById(Integer id);
    
    @Select("select * from t_student")
    @Results(
            {
                @Result(id=true,column="id",property="id"),
                @Result(column="name",property="name"),
                @Result(column="age",property="age")
            }
    )
    public List<Student> findStudents();
    
    @Select("select * from t_student where id=#{id}")
    @Results(
            {
                @Result(id=true,column="id",property="id"),
                @Result(column="name",property="name"),
                @Result(column="age",property="age"),
                @Result(column="addressId",property="address",[email protected](select="com.java1234.mappers.AddressMapper.findById"))
            }
    )
    public Student selectStudentWithAddress(int id);
    
    @Select("select * from t_student where gradeId=#{gradeId}")
    @Results(
            {
                @Result(id=true,column="id",property="id"),
                @Result(column="name",property="name"),
                @Result(column="age",property="age"),
                @Result(column="addressId",property="address",[email protected](select="com.java1234.mappers.AddressMapper.findById"))
            }
    )
    public Student selectStudentByGradeId(int gradeId);
    
    @Select("select * from t_student where id=#{id}")
    @Results(
            {
                @Result(id=true,column="id",property="id"),
                @Result(column="name",property="name"),
                @Result(column="age",property="age"),
                @Result(column="addressId",property="address",[email protected](select="com.java1234.mappers.AddressMapper.findById")),
                @Result(column="gradeId",property="grade",[email protected](select="com.java1234.mappers.GradeMapper.findById"))
            }
    )
    public Student selectStudentWithAddressAndGrade(int id);
}

// \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\StudentTest.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 StudentTest {

    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 testInsert() {
        logger.info("添加学生");
        Student student=new Student("琪琪",11);
        studentMapper.insertStudent(student);
        sqlSession.commit();
    }
    
    @Test
    public void testUpdate() {
        logger.info("更新学生");
        Student student=new Student(6,"琪琪2",12);
        studentMapper.updateStudent(student);
        sqlSession.commit();
    }
    
    @Test
    public void testDelete() {
        logger.info("删除学生");
        studentMapper.deleteStudent(6);
        sqlSession.commit();
    }
    
    @Test
    public void testGetById() {
        logger.info("通过ID查找学生");
        Student student=studentMapper.getStudentById(1);
        System.out.println(student);
    }
    
    @Test
    public void testFindStudents() {
        logger.info("查找所有学生");
        List<Student> studentList=studentMapper.findStudents();
        for(Student student:studentList){
            System.out.println(student);
        }
    }

}

// \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.GradeMapper;
import com.java1234.mappers.StudentMapper;
import com.java1234.model.Grade;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest2 {

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

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

    @Test
    public void testSelectStudentWithAddress() {
        logger.info("查找学生(带地址)");
        Student student=studentMapper.selectStudentWithAddress(3);
        System.out.println(student);
    }
    
    @Test
    public void testSelectGradeWithStudents() {
        logger.info("查找年级(带学生)");
        Grade grade=gradeMapper.findById(2);
        System.out.println(grade);
        List<Student> studentList=grade.getStudents();
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testSelectStudentWithAddressAndGrade() {
        logger.info("查找学生(带年级,带地址)");
        Student student=studentMapper.selectStudentWithAddressAndGrade(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();
    }
}

 

以上是关于MyBatis 教程03的主要内容,如果未能解决你的问题,请参考以下文章

VIM 代码片段插件 ultisnips 使用教程

markdown 打字稿...编码说明,提示,作弊,指南,代码片段和教程文章

mybatis学习(39):动态sql片段

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper

mybatis动态sql片段与分页,排序,传参的使用

MyBatis动态SQL标签用法