一、创建表
创建两个表,一个用户表,一个地址表。一个用户可以有多个地址。
--user_info表
create table user_info(
id int(2) primary key,
user_name varchar(12) unique,
password varchar(15) not null,
real_name varchar(8) not null,
age int(3)
);
--address表
create table address(
id int(2) primary key,
user_id int(2) not null,
real_name varchar(8),
mobile char(11),
address varchar(150)
);
insert into user_info values(1,'浅唱灬幸福','8912@321','王晓明',12);
insert into address values(1,1,'王小明','15516472282','山西太原');
insert into address values(2,1,'王鑫','18404905139','山西大同');
insert into address values(3,1,'任建','15333021730','山西晋城');
insert into user_info values(2,'ぅ浮生若梦〤','56701wz','王楠',36);
insert into address values(4,2,'王楠','15010303314','北京海淀');
insert into address values(5,2,'赵婕','18435224278','山西长治');
insert into user_info values(3,'街角の风铃','27w4921','李晓飞',9);
insert into address values(6,6,'刘倩','13159775555','吉林长春');
insert into address values(7,3,'刘美','13159775555','吉林长春');
二、一对一查询
一对一查询,即一个人对应一个地址,我们使用用户表id为3的数据进行举例:
1、编写UserInfo.java:
package com.jd.vo;
import java.util.List;
public class UserInfo {
private int id;
private int age;
private String realName;
private String userName;
private String password;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "[id=" + id + ", userName=" + userName + ", age=" + age + ", realName=" + realName + ", password=" + password + "]";
}
}
2、编写Address.java:
package com.jd.vo;
public class Address {
private int id;
private int userId;
private String realName;
private String mobile;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address [id=" + id + ", userId=" + userId + ", realName=" + realName + ", mobile=" + mobile + ", address=" + address + "]";
}
}
3、编写IUserInfoDao.java接口:
package com.jd.userInfo.dao;
import org.apache.ibatis.annotations.Param;
import com.jd.vo.UserInfo;
public interface IUserInfoDao {
//通过用户表的id查询用户表和地址表的信息
UserInfo select(@Param("id")int id);
}
4、编写全局配置文件mybatis-config.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>
<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://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 注册Mapper xml文件 -->
<mappers>
<mapper resource="user_info.xml" />
</mappers>
</configuration>
5、编写XML映射文件user_info.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.jd.userInfo.dao.IUserInfoDao">
<!-- type:单个元素的数据类型 -->
<resultMap type="com.jd.vo.UserInfo" id="ui">
<!-- id:对应主键 column:指定列名 property:指定把当前列中的某个数据赋给Java类中的哪个属性 -->
<id column="ui_id" property="id"/>
<result column="user_name" property="userName"/>
<result column="password" property="password"/>
<result column="ui_real_name" property="realName"/>
<result column="age" property="age"/>
<!--
一对一查询用association进行连接;
property标签属性值为UserInfo Address类型属性名;
javaType:指定address属性数据类型[不能省略]
-->
<association property="address" javaType="com.jd.vo.Address">
<id column="address_id" property="id"/>
<result column="addr_real_name" property="realName"/>
<result column="mobile" property="mobile"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="select" resultMap="ui">
select
ui.id ui_id, user_name, password, ui.real_name ui_real_name, age,
addr.id address_id, addr.real_name addr_real_name, mobile, address
from user_info ui
left join address addr on ui.id=addr.user_id
where ui.id = #{id}
</select>
</mapper>
上述sql语句id为3进行一对一查询时,输出为:
6、编写测试类Test.java:
package com.jd.test;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.jd.userInfo.dao.IUserInfoDao;
public class Test {
public static void main(String[] args) {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
org.apache.ibatis.session.SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = SqlSessionFactory.openSession();
IUserInfoDao userInfoDao = sqlSession.getMapper(IUserInfoDao.class);
//此时为一对一输出,输出id为3的唯一地址
System.out.println(userInfoDao.select(3).getAddress());
sqlSession.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出为:
三、一对多查询
一对多插叙与一对一查询类似,一个人可以有多个地址,此时更改部分文件:
1、UserInfo.java:
package com.jd.vo;
import java.util.List;
public class UserInfo {
private int id;
private int age;
private String realName;
private String userName;
private String password;
//添加List集合,将多个地址存入List集合
private List<Address> list;
public List<Address> getList() {
return list;
}
public void setList(List<Address> list) {
this.list = list;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "[id=" + id + ", userName=" + userName + ", age=" + age + ", realName=" + realName + ", password=" + password + "]";
}
}
2、XML映射文件user_info.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.jd.userInfo.dao.IUserInfoDao">
<resultMap type="com.jd.vo.UserInfo" id="ui">
<id column="ui_id" property="id"/>
<result column="user_name" property="userName"/>
<result column="password" property="password"/>
<result column="ui_real_name" property="realName"/>
<result column="age" property="age"/>
<!--
一对多用collection连接;
property:addressList为UserInfo类成员变量;
ofType:集合元素数据类型
-->
<collection property="list" ofType="com.jd.vo.Address">
<id column="address_id" property="id"/>
<result column="addr_real_name" property="realName"/>
<result column="mobile" property="mobile"/>
<result column="address" property="address"/>
</collection>
</resultMap>
<select id="select" resultMap="ui">
select
ui.id ui_id, user_name, password, ui.real_name ui_real_name, age,
addr.id address_id, addr.real_name addr_real_name, mobile, address
from user_info ui
left join address addr on ui.id=addr.user_id
where ui.id = #{id}
</select>
</mapper>
上述sql语句id为1进行一对多查询时,输出为:
3、测试类Test.java:
package com.jd.test;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.jd.userInfo.dao.IUserInfoDao;
public class Test {
public static void main(String[] args) {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
org.apache.ibatis.session.SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = SqlSessionFactory.openSession();
IUserInfoDao userInfoDao = sqlSession.getMapper(IUserInfoDao.class);
//查询List集合有多少个元素
System.out.println(userInfoDao.select(1).getList().size());
sqlSession.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
其余文件与一对一查询相同,输出为: