创建表
创建表对应的 JavaBean 对象
package com.tanlei.newer.pojo;import java.io.Serializable;import java.util.List;/** * @author:Mr.Tan * @Create:2018-11-05-10-55 **/public class Person implements Serializable { private int id; private String username; private String mobile; private Listposts; 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 getPosts() { return posts; } public void setPosts(List posts) { this.posts = posts; } @Override public String toString() { return "Person{" + "id=" + id + ", username='" + username + '\'' + ", mobile='" + mobile + '\'' + ", posts=" + posts + '}'; }}
package com.tanlei.newer.pojo;import java.io.Serializable;/** * @author:Mr.Tan * @Create:2018-11-05-10-55 **/public class Post implements Serializable { private int id; private Person person; private String title; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } 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; }}
配置文件
映射文件Person.xml
测试程序运行 main类
package com.tanlei.newer.test;import com.tanlei.newer.pojo.Person;import com.tanlei.newer.pojo.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;import java.io.IOException;import java.io.Reader;import java.util.List;/** * @author:Mr.Tan * @Create:2018-11-05-13-52 **/public class PersonMain { public static Reader reader; public static SqlSessionFactory sqlSessionFactory; static { try { reader= Resources.getResourceAsReader("config/Configure.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSession(){ return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); int postId = 1; Post post = session.selectOne("com.tanlei.newer.pojo.IPerson.getPosts", postId); System.out.println("title: "+post.getTitle()); System.out.println("userName: "+post.getPerson().getUsername()); session.close(); }}
输出结果如下: