实体类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. JVM指令重排

    指令重排的基本原则: a.程序顺序原则:一个线程内保证语义的串行性 b.volatile规则:volatile变量的写,先发生于读 c.锁规则:解锁(unlock)必然发生在随后的加锁(lock)前 ...

  2. Office 2013“永久激活信息”备份

    Office 2013“永久激活信息”备份还原简明教程及成功恢复的注意事项Office 2013永久激活后及时备份激活信息可以保证重装后快速激活.网上也有流行的各种备份工具,虽然操作简单,但是如果不理 ...

  3. ABAP 发邮件(三)

    [转自http://blog.sina.com.cn/s/blog_7c7b16000101bnxk.html]SAP ABAP 发邮件方法三(OO) *&------------------ ...

  4. (转)复习TCP/IP协议与Http协议的区别

    TPC/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据.关于TCP/IP和HTTP协议的关系,网络有一段比较容易理解的介绍:“我们在传输数据时,可以只 ...

  5. memcached 不同客户端的问题

    摘要: memcached-java客户端调用get方法获取数据失败 主要演示一下在memcached服务器端set数据之后,在客户端调用java api获取数据.不过此过程如果不慎会读取数据失败. ...

  6. 淘宝开源平台(taobao-code)使用

    偶尔之下翻到的这个东西,瞬间觉得足以解决自己在开发过程中的版本控制问题.就注册了一个试试.先是在度娘上搜寻“淘code”,进入官网之后直接注册.然后构建自己的项目,上传代码就OK了. 一.搜寻“淘co ...

  7. ButterKnife 原理解析

    一.使用方法 1.添加依赖. implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewhart ...

  8. [转]eclipse中的常用快捷键

    1.选中你要加注释的区域,用ctrl+shift+C 会加上//注释2.先把你要注释的东西选中,用shit+ctrl+/ 会加上注释3.要修改在eclispe中的命令的快捷键方式我们只需进入windo ...

  9. 【leetcode刷题笔记】Substring with Concatenation of All Words

    You are given a string, S, and a list of words, L, that are all of the same length. Find all startin ...

  10. X-real-ip与X-Forwarded-For

    经过反向代理后,客户端与web服务器之间添加了中间层,因此: 1.代理服务器使用$remote_addr拿到的会是客户端的ip 2. web服务器使用$remote_addr拿到的会是代理服务器的ip ...