您现在的位置是:首页 > 个人日记个人日记
mybatis-06-映射关系
2019-02-03 18:11:49【个人日记】482人已围观
简介一对一,一对多等多种对应关系查询数据
对应关系
一对一映射
表示两个表同时查询,获取相对应的数据
主要的表封装了另一张表的数据
package com.huangxin.model;
import java.math.BigDecimal;
public class Product {
private Integer id;
private String productName;
private BigDecimal salePrice;
private String supplier;
private String brand;
private BigDecimal costPrice;
private Message message;//主要的表封装了其它表的信息
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productName='" + productName + '\'' +
", salePrice=" + salePrice +
", supplier='" + supplier + '\'' +
", brand='" + brand + '\'' +
", costPrice=" + costPrice +
", message=" + message +
'}';
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getSalePrice() {
return salePrice;
}
public void setSalePrice(BigDecimal salePrice) {
this.salePrice = salePrice;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public BigDecimal getCostPrice() {
return costPrice;
}
public void setCostPrice(BigDecimal costPrice) {
this.costPrice = costPrice;
}
}
被封装的另一个对象信息
package com.huangxin.model;
public class Message {
private int id;
private String name;
private int age;
@Override
public String toString() {
return "Message{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public int 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 int getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
映射文件
resultMap中可以设置表中列名和对象属性的对应关系,但是用对应映射需加上另一张表封装的信息,需用association标签封装另一张表的对应关系
<?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.huangxin.mapper.ProductMapper">
<resultMap id="product" type="com.huangxin.model.Product">
<id column="id" property="id"></id>
<result column="costPrice" property="costPrice"></result>
<result column="brand" property="brand"></result>
<result column="supplier" property="supplier"></result>
<result column="salePrice" property="salePrice"></result>
<result column="productName" property="productName"></result>
<association property="message" javaType="com.huangxin.model.Message">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="age" property="age"></result>
</association>
</resultMap>
<select id="getById" parameterType="java.lang.Integer" resultMap="product">
SELECT * FROM product a,message b WHERE a.id=#{b.id}
</select>
</mapper>
注意:namespace的值一定要为对象的全限定名,否则无法使用动态代理,且报错
Junit测试
package com.huangxin.mapper;
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.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class ProductMapperTest {
private SqlSessionFactory factory;
/**
* 初始化SqlSession工厂
*/
@Before
public void init() throws IOException {
//将全局配置文件读取
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}
@Test
public void getById() {
SqlSession sqlSession = factory.openSession();
ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
System.out.println(mapper.getById(2));
sqlSession.close();
}
}
对应的控制台输出为
2018-12-29 21:09:00 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2018-12-29 21:09:00 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2018-12-29 21:09:00 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2018-12-29 21:09:00 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2018-12-29 21:09:00 [DEBUG] Opening JDBC Connection
2018-12-29 21:09:01 [DEBUG] Created connection 1885922916.
2018-12-29 21:09:01 [DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@7068e664]
2018-12-29 21:09:01 [DEBUG] > Preparing: SELECT * FROM product a,message b WHERE a.id=?
2018-12-29 21:09:01 [DEBUG] > Parameters: 2(Integer)
2018-12-29 21:09:01 [DEBUG] < Total: 4
[Product{id=2, productName='椅子', salePrice=100.00, supplier='未知', brand='未知', costPrice=50.00, message=Message{id=2, name='354', age=45345}}]
2018-12-29 21:09:01 [DEBUG] Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@7068e664]
2018-12-29 21:09:01 [DEBUG] Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@7068e664]
2018-12-29 21:09:01 [DEBUG] Returned connection 1885922916 to pool.
隔开的则为控制台输出的信息
一对多映射
配置接口
import com.huangxin.order.model.User;
public interface OrderMapper {
/**
* 查询符合信息的数据
* @return id
*/
User getAll(Integer id);
}
例如:一个用户可以有多个商品订单,这种关系为一对多
配置Mapper.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.huangxin.order.mapper.OrderMapper">
<!--Java对象的类型-->
<!--<resultMap id="名称随意" type="需要与数据库映射的model对象">-->
<!--<!–id为主键,result为普通列名称–>-->
<!--<id column="数据库列的名称" property="对象属性的名称"></id>-->
<!--<result column="普通列的名称" property="对象属性的名称"></result>-->
<!--</resultMap>-->
<resultMap id="user" type="com.huangxin.order.model.User">
<id column="id" property="id"></id>
<result column="user_name" property="userName"></result>
<result column="user_telephone" property="userTelephone"></result>
<result column="user_sex" property="userSex"></result>
<collection property="orders" ofType="com.huangxin.order.model.Orders">
<id column="oid" property="id"></id>
<result column="user_id" property="userId"></result>
<result column="create_time" property="createTime"></result>
</collection>
</resultMap>
<select id="getAll" resultMap="user">
SELECT
user.id,user.user_name,user.user_telephone,user.user_sex,
orders.oid,orders.user_id,orders.create_time
FROM user ,orders WHERE user.id=orders.user_id AND user_id=5;
</select>
</mapper>
注意:
1) collection和association应该分场合
2) collection应用于 一对多 映射
3) association应用于 一对一 映射
4) collection中的property属性集合的命名,ofType是集合中存放对象的数据类型
JavaBean多了对另一个表单储存的集合
配置User.java
文件
import java.util.List;
public class User {
private Integer id;
private String userName;
private String userTelephone;
private String userSex;
//这里表示对另一张表的查询结果,反映出一对多
"private List<Orders> orders;"
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userTelephone='" + userTelephone + '\'' +
", userSex='" + userSex + '\'' +
", orders=" + orders +
'}';
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = 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 getUserTelephone() {
return userTelephone;
}
public void setUserTelephone(String userTelephone) {
this.userTelephone = userTelephone;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
}
Junit
import com.huangxin.order.model.User;
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.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class OrderMapperTest {
private SqlSessionFactory factory;
/**
* 初始化SqlSession工厂
*/
@Before
public void init() throws IOException {
//将全局配置文件读取
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}
@Test
public void getAll() {
SqlSession sqlSession = factory.openSession();
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
User all = mapper.getAll();
System.out.println(all);
}
}
控制台输出结果为
D:\Java\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:D:\IntelliJ\lib\idea_rt.jar=2259:D:\IntelliJ\bin -Dfile.encoding=UTF-8 -classpath D:\IntelliJ\lib\idea_rt.jar;D:\IntelliJ\plugins\junit\lib\junit-rt.jar;D:\IntelliJ\plugins\junit\lib\junit5-rt.jar;D:\mybatis04\target\test-classes;D:\mybatis04\target\classes;C:\Users\Administrator\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;C:\Users\Administrator\.m2\repository\org\mybatis\mybatis\3.4.6\mybatis-3.4.6.jar;C:\Users\Administrator\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\Administrator\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.huangxin.order.mapper.OrderMapperTest,getAll
2019-01-02 15:49:50 [DEBUG] Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/C:/Users/Administrator/.m2/repository/org/mybatis/mybatis/3.4.6/mybatis-3.4.6.jar) to method java.lang.Class.checkPackageAccess(java.lang.SecurityManager,java.lang.ClassLoader,boolean)
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2019-01-02 15:49:50 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2019-01-02 15:49:50 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2019-01-02 15:49:50 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2019-01-02 15:49:50 [DEBUG] PooledDataSource forcefully closed/removed all connections.
2019-01-02 15:49:50 [DEBUG] Opening JDBC Connection
2019-01-02 15:49:50 [DEBUG] Created connection 324169305.
2019-01-02 15:49:50 [DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@13526e59]
2019-01-02 15:49:50 [DEBUG] > Preparing: SELECT user.id,user.user_name,user.user_telephone,user.user_sex, orders.oid,orders.user_id,orders.create_time FROM user ,orders WHERE user.id=orders.user_id AND user_id=5;
2019-01-02 15:49:50 [DEBUG] > Parameters:
2019-01-02 15:49:50 [DEBUG] < Total: 3
User{id=5, userName='小红', userTelephone='1234567890', userSex='女', orders=[Orders{id=7, userId='5', createTime=Tue Jan 01 19:51:03 CST 2019}, Orders{id=8, userId='5', createTime=Tue Jan 01 19:51:05 CST 2019}, Orders{id=9, userId='5', createTime=Tue Jan 01 19:51:07 CST 2019}]}
Process finished with exit code 0
多对多
多对多 是一对多和一对一进行 嵌套 组合
Tags: JavaWeb
上一篇: spring-01-快速上手
相关文章
随机图文
评论区
2024-10-03 17:05:18
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信