实体类1:

package com.etc.entity;

import java.util.List;

public class Teacher
{
private int tid;
private String tname;
private String sex;
private List<Student> students;
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Teacher [sex=" + sex + ", tid=" + tid + ", tname=" + tname
+ "]";
}
}
=================================================
实体类2: package com.etc.entity; public class Student
{
private int sid;
private String sname;
private String sex;
private Teacher teacher;//外键的关联对象
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Student [sex=" + sex + ", sid=" + sid + ", sname=" + sname
+ "]";
}
}
==================================================================
dao类1: package com.etc.dao; import java.util.List; import com.etc.entity.Teacher; public interface TeacherDao {
Teacher findById(int id);
List<Teacher> findAll();
}
===========================================
dao类2: package com.etc.dao; import com.etc.entity.Student; public interface StudentDao
{
Student findById(int id);
}
=============================================
工具类: package com.etc.utils; import java.io.InputStream;
import java.sql.Connection; 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.apache.log4j.lf5.util.Resource; //实现获取、释放mybatis数据库连接的工具类
public class MyBatisSessionFactory {
//定义常量
private static String CONFIG_FILE_LOCATION="mybatis-config.xml"; //考虑到该工具类允许被多线程执行。因为封装1个线程池,让每个线程从线程池中获取1个连接。让1个线程对应
//1条数据库连接,这样更安全
//ThreadLocal的作用:让"线程"绑定"资源",这样就不会出现多个线程同享资源的情况。更安全。牺牲内存,换取”安全“
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static InputStream is; //用于读取配置文件的流对象 private static SqlSessionFactory fac;//用于管理多个连接的工厂。一个工厂对应1个数据库。 //在该类的静态段中加载配置文件,这样可以确保只执行1次。
static
{
try {
is = Resources.getResourceAsStream(CONFIG_FILE_LOCATION);//读取配置文件
fac = new SqlSessionFactoryBuilder().build(is);//通过配置文件创建1个连接工厂
} catch (Exception e)
{
e.printStackTrace();
} }
//获取1条连接
public static SqlSession getSession()
{
SqlSession s = threadLocal.get(); //找线程池要1条连接
if(s==null) //第1次时,拿不到,则由工厂获取1条连接并放入线程池
{
s = fac.openSession();//由工厂获取1条连接并放入线程池
threadLocal.set(s);//放入线程池
}
return s;
} //关闭连接
public static void closeSession()
{
SqlSession s = threadLocal.get();//找线程池要本线程对应的连接
threadLocal.set(null);//将该连接从线程池中清除
if(s!=null)
s.close();//物理关闭连接
}
} ==================================================
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>
<typeAliases>
<typeAlias type="com.etc.entity.Student" alias="Student"/>
<typeAlias type="com.etc.entity.Teacher" alias="Teacher"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="url" value="jdbc:mysql://127.0.0.1/java?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/etc/mapper/Teacher-mapper.xml"/>
<mapper resource="com/etc/mapper/Student-mapper.xml"/>
</mappers>
</configuration>
===================================================
Student-mapper.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.etc.dao.StudentDao">
<resultMap type="Student" id="StudentMap">
<id column="sid" property="sid" />
<result column="sname" property="sname" />
<result column="sex" property="sex" />
<association property="teacher" resultMap="com.etc.dao.TeacherDao.TeacherMap"/>
</resultMap>
<select id="findById" parameterType="java.lang.Integer"
resultMap="StudentMap">
select t.tid,t.tname,t.sex,s.sid,s.sname,s.sex,s.tid
from
teacher t,student s where t.tid = s.tid
and t.tid = #{id}
</select>
</mapper>
=======================================
Teacher-mapper.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.etc.dao.TeacherDao">
<resultMap type="Teacher" id="TeacherMap">
<id column="tid" property="tid" />
<result column="tname" property="tname"/>
<result column="sex" property="sex"/>
<collection property="students" resultMap="com.etc.dao.StudentDao.StudentMap"/>
</resultMap>
<select id="findById" parameterType="java.lang.Integer" resultMap="TeacherMap">
select t.tid,t.tname,t.sex,s.sid,s.sname,s.sex,s.tid
from teacher t,student s where t.tid = s.tid
and t.tid = #{id}
</select>
<select id="findAll" resultMap="TeacherMap">
select t.tid,t.tname,t.sex,s.sid,s.sname,s.sex,s.tid
from teacher t,student s where t.tid = s.tid
</select>
</mapper>
====================================================
log4j.properties 对log4j这个jar进行文件配置: log4j.rootLogger=WARN, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
=========================================================================
测试类: package com.etc.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.etc.dao.TeacherDao;
import com.etc.entity.Student;
import com.etc.entity.Teacher;
import com.etc.utils.MyBatisSessionFactory;
public class TestMybatis
{
@Test
public void testTeacherDao()
{
//1 获取连接
SqlSession s = MyBatisSessionFactory.getSession();
//2 执行查询
Teacher t = s.getMapper(com.etc.dao.TeacherDao.class).findById(1);
System.out.println("老师是"+t);
System.out.println("学生列表如下:");
for(Student stu:t.getStudents())
{
System.out.println(stu);
}
/*List<Teacher> list = s.getMapper(com.etc.dao.TeacherDao.class).findAll();
for(Teacher t:list)
System.out.println(t);*/
//4 关闭
MyBatisSessionFactory.closeSession();
}
}
=========================================================================

  

mybatis---demo1--(1-n)----bai的更多相关文章

  1. mybatis——延迟加载

    ------------------------------------------------SqlMapConfig.xml------------------------------------ ...

  2. mybatis——使用mapper代理开发方式

    ---------------------------------------------------------------generatorConfig.xml------------------ ...

  3. eclipse + maven 搭建springMVC+Spring+mybatis 系统

    首先需要下载maven 安装maven插件.自行百度. 1: 创建maven系统 http://huxiaoheihei.iteye.com/blog/1766986 2:添加pom依赖: pom.x ...

  4. Spring+MyBatis实践—MyBatis数据库访问

    关于spring整合mybatis的工程配置,已经在Spring+MyBatis实践—工程配置中全部详细列出.在此,记录一下几种通过MyBatis访问数据库的方式. 通过sqlSessionTempl ...

  5. mybatis学习(一)一个在idea下的实例

    今天总结的是mybatis,首先说mybatis是什么? MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框架,它抽象了大量的 JDBC 冗余代 ...

  6. maven Spring+Spring MVC+Mybatis+mysql轻量级Java web开发环境搭建

    之前一直在做的一个GIS系统项目,采用了jsp+servlet框架,数据传输框架采用了apache的thrift框架,短时多传的风格还不错,但是较其他的java web项目显得有点太臃肿了,现在给大家 ...

  7. Mybatis(三)

    1 Mybaits--动态SQL 动态SQL是Mybatis强大特性之一.极大的简化我们拼装SQL的操作. 动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似. Mybatis采用功能强 ...

  8. Mybatis(二)

    1 Mybatis映射文件--增删改查 POJO类 package cn.demo1; import org.apache.ibatis.type.Alias; /** * 描述:POJO */ @A ...

  9. mybatis自定义代码生成器(Generator)——自动生成model&dao代码

    花了两天的时间研究了下mybatis的generator大体了解了其生成原理以及实现过程.感觉generator做的非常不错,给开发者也留足了空间.看完之后在generator的基础上实现了自定义的生 ...

  10. 2019-04-28 Mybatis generator逆向工程生成的Example代码分析

    今天主要对Mybatis generator生成的DAO层等进行分析,讲解Example类的使用和扩展 1.先在数据库建表 CREATE TABLE `department` ( `fid` ) NO ...

随机推荐

  1. 正则表达式 匹配符合A表达式切不符合B表达式的字符串

    有一道这样的面试题 写一个Java方法,利用正则表达式判断输入str中包含字符串”ios“或”apple“(大小写不敏感),但不包括”mediaplayer“.如果满足条件,返回所包含的字符串”ios ...

  2. 2.5链表 链式A+B

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAowAAAGpCAIAAACI2PCZAAAgAElEQVR4nO2d3YsdSX6m++/wXf8Fxu ...

  3. activiti--6-------------------------------------连线(一般数据库表的查询顺序)

    一.流程图 二.这次把流程图和Java类放在一个包下 三.代码 package com.xingshang.f_sequenceFlow; import java.io.InputStream; im ...

  4. 使用 Python 为 KVM 编写脚本,第 1 部分: libvirt

    虚拟化是目前市场上大多数服务器操作系统的标准设备.在 Linux® 的世界里,服务器虚拟化有两个主要选择:基于 Kernel 的虚拟机 (KVM) 和 Xen.KVM 是 Red Hat 和其他公司采 ...

  5. sqlalchemy——多表操作

    一对多:一对一 # one -- many class Students(Base): __tablename__ = "students" sid = Column(Intege ...

  6. Elasticsearch使用记录

    Elasticsearch使用记录 Elasticsearch的搭建方法 1.RPM方式搭建 首先去官网[https://www.elastic.co/downloads/elasticsearch# ...

  7. ARM NEON 64bit 查找表替换

    没啥效果,如果表的长度在 64个uint8_t之类,应该可以提高查表速度,否则还是C来的快 #ifdef HAVE_NEON_AARCH64 void table_lookup_AArch64_neo ...

  8. 第二十一篇 socket

    socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求 socket和file的 ...

  9. Spring 相关

    1. spring的bean的scope属性范围  参考:http://jiangshuiy.iteye.com/blog/1667316 原理分析(bean的scope属性范围) scope用来声明 ...

  10. poj 3264 Balanced Lineup【RMQ-ST查询区间最大最小值之差 +模板应用】

    题目地址:http://poj.org/problem?id=3264 Sample Input 6 3 1 7 3 4 2 5 1 5 4 6 2 2 Sample Output 6 3 0分析:标 ...