mybatis--一对多关联

今天来介绍mybatis的一对多关联

(1)首先创建数据库mybatisonetomany,并创建数据库表post和user,并向其中插入一定的数据:

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
create database mybatisonetomany;
 
 
use mybatisonetomany;
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)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
 
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关联数据查询', '在实际项目中,经常使用关联表的查询,比如:多对一,一对多等。这些查询是如何处理的呢,这一讲就讲这个问题。我们首先创建一个 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)其次,在mybatis.bean目录下创建两个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.xml文件,放在config文件夹下:

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/mybatisonetomany"/>
        <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
24
25
<?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.zk.userMaper">
    <!-- User 级联文章查询 方法配置 (一个用户对多个文章)  -->
     
    <resultMap type="User" id="resultUserMap">
        <result property="id" column="user_id" />
        <result property="username" column="username" />
        <result property="mobile" column="mobile" />
        <collection property="posts" ofType="mybatis.bean.Post" column="userid">
            <id property="id" column="post_id" javaType="int" jdbcType="INTEGER"/>   
            <result property="title" column="title" javaType="string" jdbcType="VARCHAR"/>
            <result property="content" column="content" javaType="string" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>
 
    <select id="getUser" resultMap="resultUserMap" parameterType="int">
        SELECT u.*,p.*
        FROM user u, post p
        WHERE u.id=p.userid AND id=#{user_id}
  </select>
 
</mapper>

(5)最后构建Main.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
50
51
52
package MainApp;
 
import java.io.Reader;
import java.text.MessageFormat;
import java.util.List;
 
import mybatis.bean.Post;
import mybatis.bean.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;
 
 
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 userid = 1;
            User user = session.selectOne("com.zk.userMaper.getUser", 1);
             System.out.println("username: "+user.getUsername()+",");
                     List<Post> posts = user.getPosts(); 
                     for(Post p : posts) {
                         System.out.println("Title:" + p.getTitle());
                         System.out.println("Content:" + p.getContent());               
                      
         } finally {
            session.close();
         }
    }
}

 运行结果如下:

程序结构如下:

 

posted @   leagueandlegends  阅读(280)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示