mybatis---demo1--(1-n)----bai
实体类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的更多相关文章
- mybatis——延迟加载
------------------------------------------------SqlMapConfig.xml------------------------------------ ...
- mybatis——使用mapper代理开发方式
---------------------------------------------------------------generatorConfig.xml------------------ ...
- eclipse + maven 搭建springMVC+Spring+mybatis 系统
首先需要下载maven 安装maven插件.自行百度. 1: 创建maven系统 http://huxiaoheihei.iteye.com/blog/1766986 2:添加pom依赖: pom.x ...
- Spring+MyBatis实践—MyBatis数据库访问
关于spring整合mybatis的工程配置,已经在Spring+MyBatis实践—工程配置中全部详细列出.在此,记录一下几种通过MyBatis访问数据库的方式. 通过sqlSessionTempl ...
- mybatis学习(一)一个在idea下的实例
今天总结的是mybatis,首先说mybatis是什么? MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框架,它抽象了大量的 JDBC 冗余代 ...
- maven Spring+Spring MVC+Mybatis+mysql轻量级Java web开发环境搭建
之前一直在做的一个GIS系统项目,采用了jsp+servlet框架,数据传输框架采用了apache的thrift框架,短时多传的风格还不错,但是较其他的java web项目显得有点太臃肿了,现在给大家 ...
- Mybatis(三)
1 Mybaits--动态SQL 动态SQL是Mybatis强大特性之一.极大的简化我们拼装SQL的操作. 动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似. Mybatis采用功能强 ...
- Mybatis(二)
1 Mybatis映射文件--增删改查 POJO类 package cn.demo1; import org.apache.ibatis.type.Alias; /** * 描述:POJO */ @A ...
- mybatis自定义代码生成器(Generator)——自动生成model&dao代码
花了两天的时间研究了下mybatis的generator大体了解了其生成原理以及实现过程.感觉generator做的非常不错,给开发者也留足了空间.看完之后在generator的基础上实现了自定义的生 ...
- 2019-04-28 Mybatis generator逆向工程生成的Example代码分析
今天主要对Mybatis generator生成的DAO层等进行分析,讲解Example类的使用和扩展 1.先在数据库建表 CREATE TABLE `department` ( `fid` ) NO ...
随机推荐
- go语言之接口一
在Go语言中,一个类只需要实现了接口要求的所有函数,我们就说这个类实现了该接口 我们定义了一个File类,并实现有Read().Write().Seek().Close()等方法.设 想我们有如下接口 ...
- ABAP xml
[转]Part 1 - Expressiveness of Simple TransformationsSimple Transformations are a SAP proprietary pro ...
- pycharm ctrl+滚轮调节字体大小
File --> Setting --> Editor --> General --> 勾选Change font size (zoom) with Ctrl+Mouse Wh ...
- UML建模:学习笔记(1)
UML:学习笔记(1) 事物 结构事物 类: 接口: 协作:(定义元素之间的相互作用) 用例:(在系统外部和系统交互的人) 组件:(描述物理系统的一部分) 节点:(一个节点可以被定义为运行时存在的物理 ...
- dev系列之gridview
gridview新增一行就激活编辑,及显示闪动的光标 gridView1.ShowEditor(); 隐藏Gridview表头上面的panel this.gridView1.OptionsView.S ...
- [原创]java WEB学习笔记12:一个简单的serlet连接数据库实验
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- Python3 内置函数补充匿名函数
Python3 匿名函数 定义一个函数与变量的定义非常相似,对于有名函数,必须通过变量名访问 def func(x,y,z=1): return x+y+z print(func(1,2,3)) 匿名 ...
- 第三篇、dom操作续
一.属性操作 属性操作 attributes // 获取所有标签属性 setAttribute(key,value) // 设置标签属性 getAttribute(key) // 获取指定标签属性 r ...
- JSP&EL 内置对象
JSP&EL 内置对象 转载▼ 具体的JSP和El中的内置对象见下表,由于我写在了excel中,也不知道怎么把excel发出来,就截了图. 相关问题: Q1: JSP:EL中 pageCo ...
- intel dpdk api interrupt module 中断模块介绍
声明:此文档只做学习交流使用,请勿用作其他商业用途 author:朝阳_tonyE-mail : linzhaolover@gmail.comCreate Date: 2013-7-12 11:46: ...