实体类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. antd-mobile的例子--cnode

    antd-mobile    简单的例子 预览地址 https://shenggen1987.github.io/antd-mobile-roadhog/#/crm/pages/users githu ...

  2. jQuery 中的 Deferred 和 Promises(转)

    转自:http://www.css88.com/archives/4750/comment-page-1 看前首先了解:Promises/A规范,具体可以看这里,http://www.css88.co ...

  3. eclipse新建Maven项目

    1.在eclipse中安装maven插件 2.点击File->new->maven project,出现弹窗后点击next. 接着在弹窗Select an Archetype中,filte ...

  4. codeforces 57C 思维

    题意:求出长度为n仅由1到n数字组成的非降序列与非升序列的个数. 思路:转化为求非降序列(非升序列)的个数.n个元素想象为n个离散的点x1,x2,x3,...,xn,在最开头补上一个点x0为1,在最末 ...

  5. 启动Hadoop时DFSZKFailoverController没有启动

    在启动Hadoop成功后,并没有报错信息,jps查看进程,发现DFSZKFailoverController没有启动成功,后来发现是因为防火墙的原因,关掉重试就OK了 systemctl stop f ...

  6. Sqoop- sqoop将mysql数据表导入到hive报错

    sqoop将mysql数据表导入到hive报错 [root@ip---- lib]# sqoop import --connect jdbc:mysql://54.223.175.12:3308/gx ...

  7. DIV+CSS IE6/IE7/IE8/FF兼容问题大全

    1. [代码][CSS]代码 1, FF下给 div 设置 padding 后会导致 width 和 height 增加, 但IE不会.(可用!important解决) 2, 居中问题. 1).垂直居 ...

  8. spring boot: scope (一般注入说明(一) @Autowired注解)

    实例一: DiConfig 文件: package di; import org.springframework.context.annotation.ComponentScan; import or ...

  9. string(未完待续)

    1.string字符串的长度     可以用   a.length()  来测,或者是a.size() 来测 不可以用strlen(a)来求其长度, sizeof(a)是固定值16, 求的是strin ...

  10. 具有增、删、改、查功能的vue-tree树组件

    最近写了一个具有增删改查功能的多级树组件,感觉很实用,啦啦啦啦, 废话不多说,看代码: tree.vue <template> <div> <div class=&quo ...