association标签:一对一结果合并时使用;collection:一对多结果合并时使用。
一、创建测试数据
1、建表
2、添加数据
二、具体代码
1、(ssm框架下)代码结构(association和collection的接口和sql直接写在UserMapper中)
2、mysql.properties
#mysqlæ°æ®åºè¿æ¥
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
ds.initialSize=5
ds.maxActive=30
3、mybatisConfig.xml
4、Picture.java
package com.su.mybatis.mysql.model;
public class Picture {
private Integer pictureId;
private Integer id;
private String pictureUrl;
private User user;
public Integer getPictureId() {
return pictureId;
}
public void setPictureId(Integer pictureId) {
this.pictureId = pictureId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPictureUrl() {
return pictureUrl;
}
public void setPictureUrl(String pictureUrl) {
this.pictureUrl = pictureUrl == null ? null : pictureUrl.trim();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
5、User.java
package com.su.mybatis.mysql.model;
import java.util.List;
public class User {
private Integer id;
private String name;
private String phone;
private List
6、MybatisTest.java
package com.su.mybatis.mysql.controller;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.alibaba.fastjson.JSON;
import com.su.mybatis.mysql.dao.UserMapper;
import com.su.mybatis.mysql.model.Picture;
import com.su.mybatis.mysql.model.User;
public class MybatisTest {
public static void main(String[] args) {
MybatisTest m = new MybatisTest();
m.getUserInfo();
}
public void getUserInfo() {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("mybatisConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Picture p = userMapper.testAssociation(1);
System.out.println(JSON.toJSONString(p));
User u = userMapper.testCollection(1);
System.out.println(JSON.toJSONString(u));
sqlSession.commit();
}
}
7、UserMapper.java(只粘贴相关代码,其他代码省略)
//association
Picture testAssociation(Integer pictureId);
//collection
User testCollection(Integer id);
8、UserMapper.xml
三、测试输出结果
运行MybatisTest.java中main方法,控制台输出
{"id":1,"pictureId":1,"pictureUrl":"http://image.baidu.com/1","user":{"id":1,"name":"su","phone":"18912345678"}}
{"id":1,"name":"su","phone":"18912345678","pictureList":[{"id":1,"pictureId":1,"pictureUrl":"http://image.baidu.com/1"},{"id":1,"pictureId":2,"pictureUrl":"http://image.baidu.com/2"}]}
如果有写的不对的地方,请大家多多批评指正,非常感谢!