07—mybatis注解配置一

常用注解
Select:映射查询的sql语句。
SelectProvider:Select语句的动态sql映射。允许指定一个类名和一个方法在执行时返回运行的查询语句。有两个属性:type和mehtod,type属性是类的完全限定名,method是该类中的那个方法名。

Insert:映射插入的sql语句。
InsertProvider:Insert语句的动态sql映射。允许指定一个类名和一个方法在执行时返回运行的插入语句。有两个属性:type和method,typet属性是类的完全限定名,method是该类中的那个方法名。

Update:映射更新的sql语句。
UpdateProvider:Update语句的动态sql映射,允许指定一个类名和一个方法在执行时返回运行的更新语句。有两个属性:type和method,type属性是类的完全限定名,method是该类中的那个方法名。

Delete:映射删除的sql语句。
DeleteProvider:Delete语句的动态sql映射。允许指定一个类名和一个方法在执行时返回运行的删除语句。有两个属性:type和method,type属性是类的完全限定名,method是该类中的那个方法名。

Results:多个结果映射(Result)列表。
Options:提供配置选项的附加值,它们通常在映射语句上作为附加功能配置出现。
One:复杂类型的单独属性值映射。必须指定Select属性,表示已对一。

 

一对一
1.创建表

CREATE TABLE tb_card(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(18)
);
INSERT INTO tb_card(CODE) VALUES('150801198009191038');
CREATE TABLE tb_person(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(18),
sex VARCHAR(18),
age INT,
card_id INT UNIQUE,
FOREIGN KEY (card_id) REFERENCES tb_card(id)
);
INSERT INTO tb_person(NAME,sex,age,card_id) VALUES('mingming','',28,1)

2.创建model
Card.java

package org.fkit.domain;
import java.io.Serializable;
public class Card implements Serializable {
    private Integer id;  // 主键id
    private String code; // 身份证编号
    public Card() {
        super();
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Override
    public String toString() {
        return "Card [id=" + id + ", code=" + code + "]";
    }
}
Person.java
package org.fkit.domain;
import java.io.Serializable;
public class Person implements Serializable {
    private Integer id;  // 主键id
    private String name; // 姓名
    private String sex;  // 性别
    private Integer age; // 年龄
    // 人和身份证是一对一的关系,即一个人只有一个身份证
    private Card card; 
    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Card getCard() {
        return card;
    }
    public void setCard(Card card) {
        this.card = card;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", sex=" + sex
                + ", age=" + age + "]";
    }
}

3.mapper

CardMapper.java

package org.fkit.mapper;
import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Card;
public interface CardMapper {
    @Select("SELECT * FROM TB_CARD WHERE ID = #{id} ")
    Card selectCardById(Integer id);
}

PersonMapper.java

package org.fkit.mapper;
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.mapping.FetchType;
import org.fkit.domain.Person;
public interface PersonMapper {
    @Select("SELECT * FROM TB_PERSON WHERE ID = #{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="sex",property="sex"),
        @Result(column="age",property="age"),
        @Result(column="card_id",property="card",
        one=@One(
                select="org.fkit.mapper.CardMapper.selectCardById",
                fetchType=FetchType.EAGER))
    })
    Person selectPersonById(Integer id);
}

4.mybatis-config.xml

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=123456

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.fkit.mapper.PersonMapper=DEBUG
log4j.logger.org.fkit.mapper.CardMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

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">
  <!--  XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
    <properties resource="db.properties"/>
    <!-- 指定 MyBatis 所用日志的具体实现 -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <environments default="mysql">
    <!-- 环境配置,即连接的数据库。 -->
    <environment id="mysql">
    <!--  指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
      <transactionManager type="JDBC"/>
      <!--  dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
  <mappers>
      <mapper class="org.fkit.mapper.PersonMapper"/> 
      <mapper class="org.fkit.mapper.CardMapper"/> 
  </mappers>
</configuration>

5测试

FKSqlSessionFactory.java
package org.fkit.factory;
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 FKSqlSessionFactory {
    private static SqlSessionFactory sqlSessionFactory = null;
    // 初始化创建SqlSessionFactory对象
    static{
        try {
            // 读取mybatis-config.xml文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取SqlSession对象的静态方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
    // 获取SqlSessionFactory的静态方法
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

OneToOneTest.java

package org.fkit.test;
import org.apache.ibatis.session.SqlSession;
import org.fkit.domain.Person;
import org.fkit.factory.FKSqlSessionFactory;
import org.fkit.mapper.PersonMapper;
public class OneToOneTest {
    public static void main(String[] args) throws Exception {
        // 获取Session实例
        SqlSession session = FKSqlSessionFactory.getSqlSession();
        // 获取PersonMapper实例
        PersonMapper pm = session.getMapper(PersonMapper.class);
        // 根据id查询Person对象,同时需要获得关联的Card对象
        Person p = pm.selectPersonById(1);
        // 查看查询到的Person对象
        System.out.println(p);
        // 查看查询到的关联的Card对象
        System.out.println(p.getCard());
        // 提交事务
        session.commit();
        // 关闭Session
        session.close();
    }
}

结果

DEBUG [main] - ==>  Preparing: SELECT * FROM TB_PERSON WHERE ID = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====>  Preparing: SELECT * FROM TB_CARD WHERE ID = ? 
DEBUG [main] - ====> Parameters: 1(Integer)
DEBUG [main] - <====      Total: 1
DEBUG [main] - <==      Total: 1
Person [id=1, name=mingming, sex=男, age=28]
Card [id=1, code=150801198009191038]

 

一对多
1.创建表
创建表tb_clazz

CREATE TABLE tb_clazz(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(18),
NAME VARCHAR(18)
);
INSERT INTO tb_clazz(CODE,NAME) VALUES('2017001','Java双语幼儿园中班');
创建表tb_student
CREATE TABLE tb_student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(18),
sex VARCHAR(18),
age INT,
clazz_id INT,
FOREIGN KEY (clazz_id) REFERENCES tb_clazz(id)
);

INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('aa','男',23,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('bb','女',18,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('cc','男',21,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('dd','女',20,1);

2.创建model
Clazz.java

package org.fkit.domain;
import java.io.Serializable;
import java.util.List;
public class Clazz implements Serializable {
    private Integer id; // 班级id,主键
    private String code; // 班级编号
    private String name; // 班级名称
    // 班级和学生是一对多的关系,即一个班级可以有多个学生
    private List<Student> students;
    public Clazz() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
    @Override
    public String toString() {
        return "Clazz [id=" + id + ", code=" + code + ", name=" + name + "]";
    }
}

Student.java

package org.fkit.domain;
import java.io.Serializable;
public class Student implements Serializable {
    private Integer id; // 学生id,主键
    private String name; // 姓名
    private String sex;  // 性别
    private Integer age; // 年龄
    // 学生和班级是多对一的关系,即一个学生只属于一个班级
    private Clazz clazz;
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Clazz getClazz() {
        return clazz;
    }
    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex
                + ", age=" + age + "]";
    }
}

3.mapper
ClazzMapper.java

package org.fkit.mapper;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.Clazz;
public interface ClazzMapper {
    // 根据id查询班级信息
    @Select("SELECT * FROM TB_CLAZZ  WHERE ID = #{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="code",property="code"),
        @Result(column="name",property="name"),
        @Result(column="id",property="students",
        many=@Many(
                select="org.fkit.mapper.StudentMapper.selectByClazzId",
                fetchType=FetchType.LAZY))
    })
    Clazz selectById(Integer id);        
}

StudentMapper.java

package org.fkit.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Student;
public interface StudentMapper {
    // 根据班级id查询班级所有学生
    @Select("SELECT * FROM TB_STUDENT WHERE CLAZZ_ID = #{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="sex",property="sex"),
        @Result(column="age",property="age")
    })
    List<Student> selectByClazzId(Integer clazz_id);    
}

4.mybatis-config.xml
db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mytestdb
username=root
password=root

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.fkit.mapper.ClazzMapper=DEBUG
log4j.logger.org.fkit.mapper.StudentMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

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">
  <!--  XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
    <properties resource="db.properties"/>
    <!-- 指定 MyBatis 所用日志的具体实现 -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <!-- 要使延迟加载生效必须配置下面两个属性 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <environments default="mysql">
    <!-- 环境配置,即连接的数据库。 -->
    <environment id="mysql">
    <!--  指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
      <transactionManager type="JDBC"/>
      <!--  dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
  <mappers>
      <mapper class="org.fkit.mapper.ClazzMapper"/> 
      <mapper class="org.fkit.mapper.StudentMapper"/> 
  </mappers>
</configuration>

5.测试
FKSqlSessionFactory.java

package org.fkit.factory;
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 FKSqlSessionFactory {
    private static SqlSessionFactory sqlSessionFactory = null;
    // 初始化创建SqlSessionFactory对象
    static{
        try {
            // 读取mybatis-config.xml文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取SqlSession对象的静态方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
    // 获取SqlSessionFactory的静态方法
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

结果:

DEBUG [main] - ==>  Preparing: SELECT * FROM TB_CLAZZ WHERE ID = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
1 2017001 Java双语幼儿园中班
DEBUG [main] - ==>  Preparing: SELECT * FROM TB_STUDENT WHERE CLAZZ_ID = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 4
Student [id=1, name=jack, sex=男, age=23]
Student [id=2, name=rose, sex=女, age=18]
Student [id=3, name=tom, sex=男, age=21]
Student [id=4, name=alice, sex=女, age=20]

 


多对多

1.创建表

CREATE TABLE `t_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
INSERT INTO t_student (student_name)VALUES ('小米');
INSERT INTO t_student (student_name)VALUES ('小王');
INSERT INTO t_student (student_name)VALUES ('小李');

CREATE TABLE `t_courses` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `courses_name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
INSERT INTO t_courses (courses_name)VALUES ('java');
INSERT INTO t_courses (courses_name)VALUES ('c#');
INSERT INTO t_courses (courses_name)VALUES ('php');
INSERT INTO t_courses (courses_name)VALUES ('vb');
INSERT INTO t_courses (courses_name)VALUES ('javascript');

CREATE TABLE `t_stu_cou` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_id` int(11) DEFAULT NULL,
  `cou_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `stu_id` (`stu_id`),
  KEY `cou_id` (`cou_id`),
  CONSTRAINT `t_stu_cou_ibfk_1` FOREIGN KEY (`stu_id`) REFERENCES `t_student` (`id`),
  CONSTRAINT `t_stu_cou_ibfk_2` FOREIGN KEY (`cou_id`) REFERENCES `t_courses` (`id`)
)  

INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (1,1);
INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (1,2);
INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (1,3);

INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (2,2);
INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (2,3);
INSERT INTO t_stu_cou (stu_id,cou_id)VALUES (2,4);

2.创建model
CoursesBean.java

package org.fkit.domain;
import java.io.Serializable;
import java.util.List;
public class CoursesBean implements Serializable{
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
   // 使用 List<StudentBean>集合,是说明学习这门课程的所有学生
    private List<StudentBean> student;
    public CoursesBean() {
        super();
    }
    public CoursesBean(Integer id, String name, List<StudentBean> student) {
        super();
        this.id = id;
        this.name = name;
        this.student = student;
    }
    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 List<StudentBean> getStudent() {
        return student;
    }
    public void setStudent(List<StudentBean> student) {
        this.student = student;
    }
    @Override
    public String toString() {
        return "CoursesBean [id=" + id + ", name=" + name + ", student="
                + student + "]";
    }
}

StudentBean.java

package org.fkit.domain;
import java.io.Serializable;
import java.util.List;
public class StudentBean implements Serializable{
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;    
    private List<CoursesBean> courses;
    public StudentBean() {
        super();
    }
    public StudentBean(Integer id, String name, List<CoursesBean> courses) {
        super();
        this.id = id;
        this.name = name;
        this.courses = courses;
    }
    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 List<CoursesBean> getCourses() {
        return courses;
    }
    public void setCourses(List<CoursesBean> courses) {
        this.courses = courses;
    }
    @Override
    public String toString() {
        return "StudentBean [id=" + id + ", name=" + name + ", courses="
                + courses + "]";
    }
}

3.mapper
CoursesMapper.java

package org.fkit.mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.CoursesBean;
import org.fkit.domain.StudentBean;

import java.util.List;

import org.apache.ibatis.annotations.Many;

/**
 * @author Administrator
 *
 */
public interface CoursesMapper {
    
    /**
     * 根据id查询课程
     * @param id
     * @return
     */
    @Select("select * from t_courses where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="courses_name",property="name"),
    })
    public CoursesBean findCouById(int id);
    
    /**
     * 根据学生id查询学生的所有课程
     * @param id
     * @return
     */
    @Select("select * from t_courses where id in (select cou_id from t_stu_cou where stu_id = #{id})")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="courses_name",property="name"),
    })
    public List<CoursesBean> findCoursesByStudent(int id);

    /**
     * 要求查课时,将选课的学生一并查出
     * @param id
     * @return
     */
    @Select("select * from t_courses where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="courses_name",property="name"),
        @Result(column="id",property="student",
        many=@Many(select="org.fkit.mapper.StudentMapper.findStudentByCourses",fetchType=FetchType.LAZY))
    })
    public CoursesBean findCouAndStu(int id);


}

StudentMapper.java

package org.fkit.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.CoursesBean;
import org.fkit.domain.StudentBean;

public interface StudentMapper {
    /**
     * 根据id值查询学生信息
     * @param id
     * @return
     */
    @Select("select * from t_student where id = #{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="student_name",property="name")
    })
    public StudentBean findStuById(int id);

    
    /**
     * 根据课程id查询课程的所有学生
     * @param id
     * @return
     */
    @Select(" select * from t_student where id in (select stu_id from t_stu_cou where cou_id=#{id})")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="student_name",property="name")
    })
    public List<StudentBean> findStudentByCourses(int id);
    /**
     * 要求查询学生时,将学生选择的课程查出
     * @param id
     * @return
     */
    @Select("select * from t_student where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="student_name",property="name"),
        @Result(column="id",property="courses",
        many=@Many(select="org.fkit.mapper.CoursesMapper.findCoursesByStudent",fetchType=FetchType.LAZY))
    })
    public StudentBean findStuAndCou(int id);

}

4.mybatis-config.xml
db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=123456

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.fkit.mapper.PersonMapper=DEBUG
log4j.logger.org.fkit.mapper.CardMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

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">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
    <properties resource="db.properties" />
    <!-- 指定 MyBatis 所用日志的具体实现 -->
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <!-- 为JAVA Bean起类别名 -->
    <typeAliases>
        <package name="org.fkit.domain" />
    </typeAliases>
    <environments default="mysql">
        <!-- 环境配置,即连接的数据库。 -->
        <environment id="mysql">
            <!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
            <transactionManager type="JDBC" />
            <!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
    <mappers>
        <mapper class="org.fkit.mapper.CoursesMapper" />
        <mapper class="org.fkit.mapper.StudentMapper" />
    </mappers>
</configuration>

 

5.测试
ManyToManyTest.java

package org.fkit.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.fkit.domain.CoursesBean;
import org.fkit.domain.StudentBean;
import org.fkit.mapper.CoursesMapper;
import org.fkit.mapper.StudentMapper;
public class ManyToManyTest {
    public static void main(String[] args) throws IOException {
        // 读取mybatis-config.xml文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 初始化mybatis,创建SqlSessionFactory类的实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
        // 创建Session实例
        SqlSession session = sqlSessionFactory.openSession();
        ManyToManyTest t = new ManyToManyTest();
        // 根据用户id查询用户,测试一对多
        //t.testSelectCoursesById(session);
        // 根据订单id查询订单,测试多对多
        t.testSelectStudentById(session);
        
        // 提交事务
        session.commit();
        // 关闭Session
        session.close();

    }
    public void testSelectStudentById(SqlSession session){
        // 获得UserMapper接口的代理对象
        StudentMapper sm = session.getMapper(StudentMapper.class);
        // 调用selectUserById方法
        StudentBean stu = sm.findStuAndCou(2);
        System.out.println(stu);
        // 查看查询到的user对象信息
        System.out.println(stu.getId() + " " + stu.getName());
        // 查看user对象关联的订单信息
        List<CoursesBean> CoursesList = stu.getCourses();
        for(CoursesBean item : CoursesList){
            System.out.println(item);
        }
    }
    // 测试多对多,查询订单Order(多)的时候级联查询订单的商品Article(多)  
    public void testSelectCoursesById(SqlSession session){
        // 获得OrderMapper接口的代理对象
        CoursesMapper cm = session.getMapper(CoursesMapper.class);
        // 调用selectOrderById方法
        CoursesBean course = cm.findCouAndStu(2);
        System.out.println(course);
        // 查看查询到的order对象信息
        System.out.println(course.getId() + " " + course.getName());
        // 查看order对象关联的商品信息
        List<StudentBean> studentlist = course.getStudent();
        for(StudentBean stu : studentlist){
            System.out.println(stu);
        }
    }
}

 

你最喜欢的代码:一对多

                      一对多

                      多对多

posted @ 2017-03-27 11:28  码大坑  阅读(435)  评论(0编辑  收藏  举报