今天来介绍mybatis的一对多关联
(1)首先创建数据库mybatisonetomany,并创建数据库表post和user,并向其中插入一定的数据:
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
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
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文件夹下:
<?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
<?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
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(); } } }
运行结果如下:
程序结构如下:
原文地址:https://www.cnblogs.com/longlyseul/p/11229261.html
时间: 2024-10-08 14:16:31