常用注解
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()
);
INSERT INTO tb_card(CODE) VALUES('');
CREATE TABLE tb_person(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(),
sex VARCHAR(),
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','男',,)

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);
}
}
}

你最喜欢的代码:一对多

一对多

多对多

07—mybatis注解配置一的更多相关文章

  1. MyBatis 注解配置及动态SQL

      一.注解配置 目前MyBatis支持注解配置,用注解方式来替代映射文件,但是注解配置还是有点不完善,在开发中使用比较少,大部分的企业还是在用映射文件来进行配置.不完善的地方体现在于当数据表中的字段 ...

  2. Spring Boot中使用MyBatis注解配置详解(1)

    之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...

  3. Spring Boot中使用MyBatis注解配置详解

    传参方式 下面通过几种不同传参方式来实现前文中实现的插入操作. 使用@Param 在之前的整合示例中我们已经使用了这种最简单的传参方式,如下: @Insert("INSERT INTO US ...

  4. 08—mybatis注解配置二

    动态sql mybatis的注解也支持动态sql.mybatis提供了各种注解,如@InsertProvider.@UpdateProvider.@DeleteProvider和@SelectProv ...

  5. Spring Boot教程(三十九)使用MyBatis注解配置详解(2)

    增删改查 MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,在之前的示例中演示了@Insert,下面针对User表做一组最基本的增删改查作为示例: public interface U ...

  6. Spring Boot教程(三十八)使用MyBatis注解配置详解(1)

    之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...

  7. MyBatis注解配置动态SQL

    MySQL创建表 DROP TABLE IF EXISTS `tb_employee`; CREATE TABLE `tb_employee` ( `id` int(11) NOT NULL AUTO ...

  8. 09—mybatis注解配置join查询

    今天来聊mybatis的join查询,怎么说呢,有的时候,join查询确实能提升查询效率,今天举个left join的例子,来看看mybatis的join查询. 就不写的很细了,把主要代码贴出来了. ...

  9. MyBatis 注解配置

    Employee package com.example.demo.domain; import java.io.Serializable; public class Employee impleme ...

随机推荐

  1. jstack使用

    top -p 22072 -H  -p:查看某个进程 -H列出所有的线程 printf '%x' 22398 (16进制线程号) sudo -u tomcat jstack 22072 | grep ...

  2. spring中的bean的生命周期

    bean的生命周期:bean的创建 —— 初始化 ——销毁的过程 容器管理bean的生命周期,我们可以自定义初始化和销毁方法,容器在bean进行到当前生命周期就会调用我们的方法 在xml配置文件中是在 ...

  3. Netty学习篇①

    什么是netty Netty封装了JDK自带的NIO,运用起来更加简单快速,Netty是一个异步事件驱动的网络应用框架,让开发更加简便 Netty相比JDK自带的NIO的优点 Netty的api调用简 ...

  4. 运行servlet跳转页面变成了下载界面,或者中文乱码

    1.是这个地方的问题,敲错了Setvlet不能识别HTML文件,所以变成了下载.2.这个也是防止中文乱码 //设置响应内容类型response.setContentType("text/ht ...

  5. 【LOJ】#3096. 「SNOI2019」数论

    LOJ#3096. 「SNOI2019」数论 如果\(P > Q\)我们把\(P\)和\(Q\)换一下,现在默认\(P < Q\) 这个时候每个合法的\(a_i\)都可以直接落到\(Q\) ...

  6. mysql 查询最佳实践

    (1)负向条件查询不能使用索引 select * from order where status!=0 and stauts!=1 not in/not exists都不是好习惯 (2)前导模糊查询不 ...

  7. MACD中短线交易系统

    1.MA5.MA10金叉,且股价收盘站稳5日均线 2.MACD金叉 3.MACD红绿柱 a.MACD红柱发散,表示多头力量增强,此时买入或加仓 b.MACD红柱收缩,表示多头力量减弱,此时卖出或减仓 ...

  8. HttpContext is null

    HttpContext context1 = System.Web.HttpContext.Current; HttpContext context2 = System.Runtime.Remotin ...

  9. VBA精彩代码分享-3

    在开发VBA程序中,我们可能会需要用代码处理VBA工程,包括启用VBA工程访问,启用所有宏,动态插入代码,动态删除代码,动态添加引用和自动创建模块等等,本次的分享内容便以这些为主. 启用VBA工程访问 ...

  10. 4. Java入门程序

    以eclipse为例,建立一个简单的Java程序. 首先启动eclipse,进入到如下主页面: 新建一个项目,选择“File-New-Java Project”: 弹出了一个如下页面,假设命名为Tes ...