数据库
tb_student
CREATE TABLE `tb_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`card_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `card_id` (`card_id`),
CONSTRAINT `card_id` FOREIGN KEY (`card_id`) REFERENCES `tb_studentidcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_student
-- ----------------------------
INSERT INTO `tb_student` VALUES ('1', 'limin', 'f', '1');
INSERT INTO `tb_student` VALUES ('2', 'jack', 'm', '2');
tb_studentidcard
CREATE TABLE `tb_studentidcard` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(8) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_studentidcard
-- ----------------------------
INSERT INTO `tb_studentidcard` VALUES ('1', '18030128');
INSERT INTO `tb_studentidcard` VALUES ('2', '18030135');
POJO类
package com.ssm.po;
public class Student {
private Integer id;
private String name;
private String sex;
private StudentIdCard studentIdCard;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public StudentIdCard getStudentIdCard() {
return studentIdCard;
}
public void setStudentIdCard(StudentIdCard studentIdCard) {
this.studentIdCard = studentIdCard;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", studentIdCard=" + studentIdCard + "]";
}
}
package com.ssm.po;
public class StudentIdCard {
private Integer id;
private String code;
public StudentIdCard() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "StudentIdCard [id=" + id + ", code=" + code + "]";
}
}
映射文件
StudentIdCardMapper.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.ssm.mapper.StudentIdCardMapper">
<select id="findStudentIdCardById" parameterType="Integer" resultType="com.ssm.po.StudentIdCard">
select * from tb_studentidcard where id = #{id}
</select>
</mapper>
StudentMapper.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.ssm.mapper.StudentMapper">
<select id="findStudentById" parameterType="Integer" resultMap="StudentIdCardWithStudentResult">
select * from tb_student where id = #{id}
</select>
<resultMap type="com.ssm.po.Student" id="StudentIdCardWithStudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<association property="studentIdCard" column="card_id" javaType="com.ssm.po.StudentIdCard"
select = "com.ssm.mapper.StudentIdCardMapper.findStudentIdCardById" >
</association>
</resultMap>
</mapper>
核心配置文件
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>
<properties resource="db.properties"></properties>
<!-- 延迟加载 -->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!-- 配置环境,默认的环境id为mysql -->
<environments default="mysql">
<!-- 配置id为mysql的数据库环境 -->
<environment id="mysql">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper的环境 -->
<mappers>
<mapper resource="com/ssm/mapper/StudentIdCardMapper.xml"/>
<mapper resource="com/ssm/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=root
工具类
package com.ssm.util;
import java.io.IOException;
import java.io.InputStream;
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 MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
log4j.properties
#Global logging configuration#
log4j.rootLogger=ERROR,stdout
#mybatis logging configuration#
Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
测试
package com.ssm.test;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.ssm.po.Student;
import com.ssm.util.MybatisUtil;
public class MybatisAssociatedTest {
@Test
public void findStudentByIdTest() {
SqlSession sqlSession = MybatisUtil.getSession();
Student student = sqlSession.selectOne("com.ssm.mapper.StudentMapper.findStudentById", 1);
System.out.println(student.toString());
sqlSession.close();
}
}