mybatis--多对一关联
(1)首先,创建数据库mybatismanytoone并插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | create database mybatismanytoone; use mybatismanytoone; create table user ( id int (10) unsigned not null auto_increment, username varchar (64) not null default '' , mobile int (10) unsigned not null default '0' , created datetime not null default '0000-00-00 00:00:00' , primary key (id) ); INSERT INTO user VALUES ( '1' , 'yiibai' , '100' , '2015-09-23 20:11:23' ); CREATE TABLE post( post_id int (10) unsigned NOT NULL AUTO_INCREMENT, userid int (10) unsigned NOT NULL , title varchar (254) NOT NULL DEFAULT '' , content text, created datetime NOT NULL DEFAULT '0000-00-00 00:00:00' , PRIMARY KEY (post_id) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; INSERT INTO post VALUES ( '1' , '1' , 'MyBatis关联数据查询' , '在实际项目中,经常使用关联表的查询,比如:多对一,一对多等。这些查询是如何处理的呢,这一讲就讲这个问题。<br>我们首先创建一个 post 表,并初始化数据.' , '2015-09-23 21:40:17' ); INSERT INTO post VALUES ( '2' , '1' , 'MyBatis开发环境搭建' , '为了方便学习,这里直接建立java 工程,但一般都是开发 Web 项目。' , '2015-09-23 21:42:14' ); INSERT INTO post VALUES ( '3' , '2' , '这个是别人发的' , 'content,内容...' , '0000-00-00 00:00:00' ); |
(2)接着我们创建两个java bean Post.java和User.java
Post.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package mybatis.bean; import java.io. Serializable ; public class Post implements Serializable { private int id; private User user ; private String title; private String content; public int getId() { return id; } public void setId( int id) { this.id = id; } public User getUser() { return user ; } public void setUser( User user ) { this. user = user ; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } |
User.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package mybatis.bean; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable{ private int id; private String username; private String mobile; private List<Post> posts; public int getId() { return id; } public void setId( int id) { this .id = id; } public String getUsername() { return username; } public void setUsername(String username) { this .username = username; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this .mobile = mobile; } public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this .posts = posts; } @Override public String toString() { return "User [id=" + id + ", name=" + username + "]" ; } } |
(3)其次,我们创建config/config.xml配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?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> <typeAliases> <typeAlias alias= "User" type= "mybatis.bean.User" /> <typeAlias alias= "Post" type= "mybatis.bean.Post" /> </typeAliases> <environments default = "development" > <environment id= "development" > <transactionManager type= "JDBC" /> <dataSource type= "POOLED" > <property name= "driver" value= "com.mysql.jdbc.Driver" /> <property name= "url" value= "jdbc:mysql://localhost:3306/mybatismanytoone" /> <property name= "username" value= "root" /> <property name= "password" value= "123456" /> </dataSource> </environment> </environments> <mappers> <!-- // power by http://www.yiibai.com --> <mapper resource= "mybatis/bean/User.xml" /> </mappers> </configuration> |
(4)再次,我们创建User.xml文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?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.mybatis.userMaper" > <!-- User 级联文章查询 方法配置 (多个文章对一个用户) --> <resultMap type= "Post" id= "resultPostsMap" > <result property= "id" column= "post_id" /> <result property= "title" column= "title" /> <result property= "content" column= "content" /> <association property= "user" javaType= "User" > <id property= "id" column= "userid" /> <result property= "username" column= "username" /> <result property= "mobile" column= "mobile" /> </association> </resultMap> <select id= "getPosts" resultMap= "resultPostsMap" parameterType= "int" > SELECT u.*,p.* FROM user u, post p WHERE u.id=p.userid AND p.post_id=#{post_id} </select> </mapper> |
(5)最后,我们执行main函数,进行查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package Main; import java.io.Reader; import mybatis.bean.Post; 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 Main { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader( "config/config.xml" ); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SqlSession session = sqlSessionFactory.openSession(); try { int postId = 1 ; Post post = session.selectOne( "com.zk.userMaper" , postId); System.out.println( "title: " +post.getTitle()); System.out.println( "userName: " +post.getUser().getUsername()); } finally { session.close(); } } } |
查询结果如下图显示:
程序结构如下图所示:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)