下面三个案例都需要在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>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 懒加载
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings> -->
<environments default="development">
<environment id="development">
<!--
type="JDBC":指直接简单使用了JDBC的提交和回滚设置
type="POOLED":指让容器实现对事务的管理
-->
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="caoxuekun" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
<mapper resource="usersMapper.xml"/>
<mapper resource="relationMapping.xml"/>
<mapper resource="cache.xml"/>
<mapper class="com.interfaceMybatis.UsersMapper"/>
<mapper class="com.interfaceMybatis.mapping.OneToOne" />
<mapper class="com.interfaceMybatis.mapping.OneToMany" />
<mapper class="com.interfaceMybatis.mapping.ManyToMany" /></mappers>
</configuration>
一对一:
实体:
package com.entity.oneToOne;
import java.io.Serializable;
public class Person implements Serializable{
private Integer id;
private String name;
private String sex;
private Integer age;
private Card card;
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;
}
}
package com.entity.oneToOne;
import java.io.Serializable;
public class Card implements Serializable{
private Integer id;
private String code;
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;
}
}
数据库表:
CREATE TABLE `tb_person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`sex` varchar(100) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`card_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `card_id` (`card_id`),
CONSTRAINT `tb_person_ibfk_1` FOREIGN KEY (`card_id`) REFERENCES `tb_card` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `tb_card` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
注解配置:
package com.interfaceMybatis.mapping;
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 com.entity.oneToOne.Card;
import com.entity.oneToOne.Person;
public interface OneToOne {
@Select("select * from tb_card where id = #{id}")
Card selectCardById(Integer id);
@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="com.interfaceMybatis.mapping.OneToOne.selectCardById",
fetchType=FetchType.EAGER
))
})
Person selectPersonById(Integer id);
}
测试:
public static SqlSession getSqlSession() {
// mybatis的配置文件
String resource = "conf.xml";
// 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
// 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
// Reader reader = Resources.getResourceAsReader(resource);
// 构建sqlSession的工厂
// SqlSessionFactory sessionFactory = new
// SqlSessionFactoryBuilder().build(reader);
// 创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
return session;
}
//oneToOne
public static void oneToOne(Integer id){
SqlSession session = getSqlSession();
OneToOne oto = session.getMapper(OneToOne.class);
// Card card = oto.selectCardById(id);
// System.out.println(card.getId()+"==="+card.getCode());
Person person = oto.selectPersonById(id);
System.out.println(person.getId()+"==="+person.getName()+"==="+person.getSex()+"==="+person.getAge()+"==="+person.getCard().getId()+"==="+person.getCard().getCode());
session.commit();
session.close();
}
public static void main(String[] args) {
oneToOne(1);
// oneToMany(1);
// manyTomany();
}
一对多
实体:
package com.entity.oneToMany;
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 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;
}
}
package com.entity.oneToMany;
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private Clazz clazz;
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;
}
}
数据库:
CREATE TABLE `tb_clazz` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
CREATE TABLE `tb_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`sex` varchar(18) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`clazz_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clazz_id` (`clazz_id`),
CONSTRAINT `tb_student_ibfk_1` FOREIGN KEY (`clazz_id`) REFERENCES `tb_clazz` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
注解配置:
package com.interfaceMybatis.mapping;
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 com.entity.oneToMany.Clazz;
import com.entity.oneToMany.Student;
public interface OneToMany {
@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 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="com.interfaceMybatis.mapping.OneToMany.selectByClazzId",
fetchType=FetchType.LAZY
)
)
})
Clazz selectClazzByIdToManyStudent(Integer id);
}
测试:
public static SqlSession getSqlSession() {
// mybatis的配置文件
String resource = "conf.xml";
// 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
// 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
// Reader reader = Resources.getResourceAsReader(resource);
// 构建sqlSession的工厂
// SqlSessionFactory sessionFactory = new
// SqlSessionFactoryBuilder().build(reader);
// 创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
return session;
}
//OneToMany
public static void oneToMany(Integer id){
SqlSession session = getSqlSession();
OneToMany otm = session.getMapper(OneToMany.class);
Clazz clazz = otm.selectClazzByIdToManyStudent(id);
System.out.println(clazz.getId()+"=="+clazz.getName()+"==="+clazz.getCode());
for(Student s:clazz.getStudents()){
System.out.println(s.getId()+"==="+s.getName()+"==="+s.getSex()+"==="+s.getAge());
}
session.commit();
session.close();
}
public static void main(String[] args) {
// oneToOne(1);
oneToMany(1);
// manyTomany();
}
多对多
实体:
package com.entity.manyToMany;
import java.io.Serializable;
import java.util.List;
public class Article implements Serializable{
private Integer id;//商品id
private String name;//商品名称
private Double price;//商品价格
private String remark;//商品描述
private List<Order> orders;
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
package com.entity.manyToMany;
import java.io.Serializable;
import java.util.List;
public class Order implements Serializable {
private Integer id;//订单id
private String code;//订单编号
private Double total;//订单总金额
private User user;
private List<Article> articles;//一个订单可包含多种商品
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 Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
}
package com.entity.manyToMany;
import java.io.Serializable;
import java.util.List;
public class User implements Serializable{
private Integer id;
private String username;
private String loginname;
private String password;
private String phone;
private String address;//收获地址
private List<Order> orders;//订单
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
数据库:
//多对多
create table tb_user(
id int PRIMARY key auto_increment,
username VARCHAR(100),
loginname varchar(100),
password VARCHAR(100),
phone varchar(18)
);
create table tb_article(
id int primary key auto_increment,
name VARCHAR(100),
price double,
remark VARCHAR(18)
);
create table tb_order(
id int primary key auto_increment,
code VARCHAR(180),
total double,
user_id int,
FOREIGN key(user_id) REFERENCES tb_user(id)
);
//tb_order和tb_article的中间表
create table tb_item(
order_id int,
article_id int,
amout int,
PRIMARY key(order_id,article_id),
FOREIGN key(order_id) REFERENCES tb_order(id),
FOREIGN key(article_id) REFERENCES tb_article(id)
);
注解配置:
package com.interfaceMybatis.mapping;
import java.util.List;
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 org.apache.ibatis.mapping.FetchType;
import com.entity.manyToMany.Article;
import com.entity.manyToMany.Order;
import com.entity.manyToMany.User;
import com.sun.scenario.effect.impl.prism.PrImage;
public interface ManyToMany {
@Select("select * from tb_user where id = #{id}")
User selectUserById(Integer id);
@Select("select * from tb_article where id in (select article_id from tb_item where order_id = #{id})")
List<Article> selectArticles(Integer id);
@Select("select * from tb_order where id = #{id}")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="code",property="code"),
@Result(column="total",property="total"),
@Result(column="user_id",property="user",
one=@One(
select="com.interfaceMybatis.mapping.ManyToMany.selectUserById",
fetchType=FetchType.EAGER
)
),
@Result(column="id",property="articles",
many=@Many(
select="com.interfaceMybatis.mapping.ManyToMany.selectArticles",
fetchType=FetchType.LAZY
)
)
})
Order selectOrderById(Integer id);
@Select("select * from tb_order where id in(select order_id from tb_item where article_id = #{id})")
List<Order> selectOrders(Integer id);
@Select("select * from tb_article where id = #{id}")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="price",property="price"),
@Result(column="remark",property="remark"),
@Result(column="id",property="orders",
many=@Many(
select="com.interfaceMybatis.mapping.ManyToMany.selectOrders",
fetchType=FetchType.LAZY
)
)
})
Article selectArticleById(Integer id);
}
测试:
public static SqlSession getSqlSession() {
// mybatis的配置文件
String resource = "conf.xml";
// 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
// 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
// Reader reader = Resources.getResourceAsReader(resource);
// 构建sqlSession的工厂
// SqlSessionFactory sessionFactory = new
// SqlSessionFactoryBuilder().build(reader);
// 创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
return session;
}
//manyTomany
public static void manyTomany(){
SqlSession session = getSqlSession();
ManyToMany mtm = session.getMapper(ManyToMany.class);
Order order = mtm.selectOrderById(1);
System.out.println("order : "+order.getId()+"==="+order.getCode()+"==="+order.getTotal());
System.out.println("=====Articles=====");
for(Article a : order.getArticles()){
System.out.println(a.getId()+"==="+a.getName()+"==="+a.getRemark()+"==="+a.getPrice());
}
System.out.println("\r\n========\r\n");
Article article = mtm.selectArticleById(2);
System.out.println("article:"+article.getId()+"==="+article.getName()+"==="+article.getRemark()+"==="+article.getPrice());
for(Order o:article.getOrders()){
System.out.println("order :"+o.getId()+"==="+o.getCode());
}
}
public static void main(String[] args) {
// oneToOne(1);
// oneToMany(1);
manyTomany();
原文:https://blog.csdn.net/caoxuekun/article/details/76944001