Spring事务处理、Spring与RESTful
#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(""); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理