本实例使用用户(User)和博客(Post)的例子做说明: 一个用户可以有多个博客, 一个博客只对应一个用户
一. 例子(本实体采用maven构建):
1. 代码结构图:
2. 数据库:
t_user 用户表:
CREATE TABLE `t_user` (
`t_id` int(11) NOT NULL AUTO_INCREMENT,
`t_name` varchar(26) NOT NULL,
`t_age` int(11) NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
post 博客表:
CREATE TABLE `t_post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`url` varchar(255) NOT NULL,
`uid` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `u_id` (`uid`),
CONSTRAINT `u_id` FOREIGN KEY (`uid`) REFERENCES `t_user` (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
3. 博客实体:
/**
* 博客类
*/
public class Post { private Integer id;
private String url;
private Integer uid; private User user; public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public Integer getUid() {
return uid;
} public void setUid(Integer uid) {
this.uid = uid;
} @Override
public String toString() {
return "Post{" +
"id=" + id +
", url='" + url + '\'' +
", uid=" + uid +
", user=" + user +
'}';
}
}
4. 用户实体:
/**
* 用户类
*/ public class User { private String tName;
private Integer tAge;
private Integer tid;
private List<Post> posts; public List<Post> getPosts() {
return posts;
} public void setPosts(List<Post> posts) {
this.posts = posts;
} public Integer getTid() {
return tid;
} public void setTid(Integer tid) {
this.tid = tid;
} public String gettName() {
return tName;
} public void settName(String tName) {
this.tName = tName;
} public Integer gettAge() {
return tAge;
} public void settAge(Integer tAge) {
this.tAge = tAge;
} @Override
public String toString() {
return "User{" +
"tName='" + tName + '\'' +
", tAge=" + tAge +
", tid=" + tid +
", posts=" + posts +
'}';
}
}
5. 一对多实体配置: UserMapper.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.yiibai.mybatis.models.UserMapper"> <!-- 根据id查询User, 关联将Post查询出来 -->
<select id="getUser" resultMap="getUsersMap">
select * from t_user u,t_post p where u.t_id=p.uid and u.t_id=#{t_id}
</select> <resultMap type="User" id="getUsersMap">
<id column="t_id" property="tid"></id>
<result column="t_name" property="tName"/>
<result column="t_age" property="tAge"/>
<!-- 一对多的关系 -->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="posts" ofType="Post">
<id column="id" property="id"/>
<result column="url" property="url"/>
<result column="uid" property="uid"/> </collection>
</resultMap> </mapper>
6. 多对一实体配置:PostMapper.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.yiibai.mybatis.models.PostMapper"> <!-- 根据id查询Post, 关联将User查询出来 -->
<select id="getPost" resultMap="getPostMap">
select * from t_user u,t_post p where u.t_id=p.uid and p.id=#{id}
</select> <resultMap type="Post" id="getPostMap">
<id column="id" property="id"></id>
<result column="url" property="url"/>
<result column="uid" property="uid"/>
<!-- 多对一的关系 -->
<!-- property: 指的是属性的值, javaType:指的是属性的类型-->
<association property="user" javaType="User">
<id column="t_id" property="tid"/>
<result column="t_name" property="tName"/>
<result column="t_age" property="tAge"/> </association>
</resultMap> </mapper>
7. mybatis配置文件: Configure.xml
<?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> <properties resource="sql.properties"/> <settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<typeAlias alias="User" type="models.User"/>
<typeAlias alias="Post" type="models.Post"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments> <mappers>
<!-- // power by http://www.yiibai.com -->
<mapper resource="UserMapper"/> <mapper resource="PostMapper"/>
</mappers>
</configuration>
8. 测试文件:
import models.Post;
import models.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;
import org.junit.Before; import java.io.InputStream; public class Test { private SqlSessionFactory ssf; @Before
public void initSF() throws Exception {
String resource = "Configure";
InputStream inputStream = Resources.getResourceAsStream(resource);
ssf = new SqlSessionFactoryBuilder().build(inputStream);
} @org.junit.Test //多对一关联查询
public void selectPostById() {
SqlSession session = ssf.openSession();
User user = session.selectOne("com.yiibai.mybatis.models.UserMapper.getUser", 1);
System.out.println(user.toString());
session.close(); } @org.junit.Test //一对多关联查询
public void selectUserById() {
SqlSession session = ssf.openSession();
Post post = session.selectOne("com.yiibai.mybatis.models.PostMapper.getPost", 1);
System.out.println(post.toString());
session.close();
}
}
9:maven配置
<dependencies>
<!--dependency>
<groupId>com.ggband</groupId>
<artifactId>[the artifact id of the block to be mounted]</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency--> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <dependency>
<groupId>org.testifyproject.junit4</groupId>
<artifactId>junit4-core</artifactId>
<version>1.0.3</version>
</dependency> </dependencies>