首页 > 编程语言 > 详细

Spring事务处理、Spring与RESTful

时间:2020-06-11 16:49:58      阅读:44      评论:0      收藏:0      [点我收藏+]

#Mybatis关联映射

什么是?将数据库中有关联关系的表,以实体对象引用的方式体现出来

 

关联方式:

-关联单个对象

-关联多个对象

 

class User{

  ...

  private List<Book> books;

}

 

class Book{

  ...

  private User user;

}

 

什么时候用?

业务需要对数据库进行关联查询的时候.

 

可以通过一条SQL语句完成关联查询,也可以通过两条SQL语句进行关联查询

##案例:通过userId查询用户信息和关联笔记本信息

1.User 实体类

private List<Book> books;

技术分享图片

 

 

2.定义Dao接口,配置Mapper文件

-RelationMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!-- Dept.xml 在com.tarena.entity 包中  -->  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<!-- namespace 的值是 DeptMapper 接口
  每个Mapper 接口对应一个配置文件  -->
<mapper namespace="cn.tedu.cloud_note.dao.RelationDao">
    <!-- 使用两条SQL语句加载数据 -->
    <select id="findUserAndBooks" parameterType="String" resultMap="userMap1">
        select * from cn_user
                        where cn_user_id=#{id}
    </select>
    <resultMap type="cn.tedu.cloud_note.entity.User" id="userMap1">
        <id property="cn_user_id" column="cn_user_id" />
        <result property="cn_user_name" column="cn_user_name"/>
        <!-- 指定books属性是一个List集合 ,泛型为Book -->
        <!-- javaType是返回类型 -->
        <collection property="books" 
        javaType="java.util.List"
        ofType="cn.tedu.cloud_note.entity.Book"
        select="findBooks"
        column="cn_user_id">
        </collection>
    </resultMap>
    <select id="findBooks" parameterType="String" resultType="cn.tedu.cloud_note.entity.Book">
        select * from cn_notebook
                        where cn_user_id=#{userId}
    </select>
</mapper>

 

3.定义测试类验证查询结果

TestBase.java

package cn.tedu.cloud_note.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public abstract class TestBase {
    public ApplicationContext getContext() {
        String[] conf = {
                "conf/spring-mvc.xml",
                "conf/spring-mybatis.xml"
        };
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        return ac;
    }
}

TestRelationDao.java

package cn.tedu.cloud_note.test.dao;

import org.junit.Before;
import org.junit.Test;

import cn.tedu.cloud_note.dao.RelationDao;
import cn.tedu.cloud_note.entity.User;
import cn.tedu.cloud_note.test.TestBase;

public class TestRelationDao extends TestBase{
    private RelationDao rdao;
    
    @Before
    public void init() {
        rdao = super.getContext().getBean("relationDao",RelationDao.class);
    }
    @Test
    public void test() {
        User user = rdao.findUserAndBooks("");
    }
    
}

 

Spring事务处理、Spring与RESTful

原文:https://www.cnblogs.com/gol2q/p/13093505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!