mybatis入门
1.什么是MyBatis ?
2.MyBatis 的入门案例

源码介绍:
1.jar包

2.其次,我们要准备mybatis-config.xml(mybatis的配置文件)
<?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="cn.zhang.entity.Student" alias="Student" />
<!--方式二: 拿当前指定包下的简单类名作为别名 -->
<!-- <package name="cn.zhang.entity"/> -->
</typeAliases>
<environments default="development">
<environment id="development">
<!-- 使用jdbc的事务 -->
<transactionManager type="JDBC" />
<!-- 使用自带的连接池 -->
<dataSource type="POOLED">
<!-- 我用的Oracle数据库 -->
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="zhangzong" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/zhang/dao/StudentDAO.xml" />
</mappers>
</configuration>
3.Student.java (实体类)
package cn.zhang.entity; import java.util.Date; /**
* 学生实体类
*
*/
public class Student {
private Integer stuno;
private String stuname;
private Integer stuage;
private Date studate; public String toString() {
return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
+ stuage + ", studate=" + studate + "]";
} public Integer getStuno() {
return stuno;
} public void setStuno(Integer stuno) {
this.stuno = stuno;
} public String getStuname() {
return stuname;
} public void setStuname(String stuname) {
this.stuname = stuname;
} public Integer getStuage() {
return stuage;
} public void setStuage(Integer stuage) {
this.stuage = stuage;
} public Date getStudate() {
return studate;
} public void setStudate(Date studate) {
this.studate = studate;
} }
4.StudentDao.java
package cn.zhang.dao; import java.io.IOException;
import java.util.List; import cn.zhang.entity.Student; public interface StudentDao {
/**
* 新增学生
*
* @param stu
* @return
* @throws IOException
*/
public int add(Student stu) throws IOException; /**
* 删除学生
* @param id
* @return
* @throws IOException
*/
public int delStu(int id) throws IOException; /**
* 查询所有记录
* @return
* @throws IOException
*/
public List<Student> findAll() throws IOException; /**
* 按照学生姓名查询学生集合(实体)
* @param stu
* @return
* @throws IOException
*/
public List<Student> findStudntByName(Student stu) throws IOException; /**
* 按照学生姓名查询学生集合(字符串)
* @param stuname
* @return
* @throws IOException
*/
public List<Student> findStudntByName(String stuname) throws IOException; }
5.StudentDaoImpl.java
package cn.zhang.dao.impl; import java.io.IOException;
import java.io.Reader;
import java.util.List; 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 cn.zhang.dao.StudentDao;
import cn.zhang.entity.Student;
import cn.zhang.util.MybatisUtil; public class StudentDaoImpl implements StudentDao {
SqlSession session; public StudentDaoImpl() throws IOException {
session = MybatisUtil.getSession();
} /**
* 添加
*/
@Override
public int add(Student stu) throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 获取Session
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = build.openSession();
int count = session.insert("insertStudent", stu);
session.commit();
session.close();
return count;
} /**
* 模糊查询(字符串)
*/
public List<Student> findStudntByName(String stuname) throws IOException {
List<Student> list = session.selectList("findStudentByName", stuname);
session.close();
return list;
} /**
* 模糊查询(实体)
*/ public java.util.List<Student> findStudntByName(Student stu)
throws IOException {
List<Student> list = session.selectList("findStudentByName", stu);
session.close();
return list;
} /**
* 查询所有
*/
public java.util.List<Student> findAll() throws IOException {
List<Student> list = session.selectList("findAll");
session.close();
return list;
} /**
* 删除
*/
public int delStu(int id) throws IOException {
int result = session.delete("delStudent", id);
session.commit();
session.close();
return result;
} }
6.StudentDAO.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="cn.zhang.dao">
<!-- 获得自增值 -->
<insert id="insertStudent" parameterType="Student">
insert into student(stuno,stuname,stuage,studate)
values(mybatis.nextval,#{stuname},#{stuage},#{studate})
<!-- sqlserver 和4Mysql 只有自自增 自增时机和insert时机: 先insert返回自增值 Oracle先产生一个自增值,然后再执行insert -->
<selectKey keyProperty="stuno" resultType="int">
select mybatis.currval from dual
<!-- select @@identity --><!--MySQL和SQLServer中的用法 -->
</selectKey>
</insert> <!--删除学生 -->
<delete id="delStudent">
delete from student where stuno=#{xxx}<!-- #{xxx}随便写,起到一个占位的作用 -->
</delete> <!-- 查询所有 -->
<select id="findAll" resultType="Student">
select * from student
</select> <!--模糊查询 --><!-- $方式无法防止Sql注入 ,#方式能够很大程度防止sql注入 -->
<select id="findStudentByName" resultType="Student">
<!-- select * from student where stuname like concat('%',#{stuname},'%') -->
select * from student where stuname like '%${value}%'
</select> </mapper>
7.MybatisUtil.java
package cn.zhang.util; import java.io.IOException;
import java.io.Reader; 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 String config = "mybatis-config.xml";
static Reader reader;
static {
try {
reader = Resources.getResourceAsReader(config);
} catch (IOException e) {
e.printStackTrace();
}
}
private static SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(reader); // 提供一个可以获取到session的方法
public static SqlSession getSession() throws IOException { SqlSession session = factory.openSession();
return session;
}
}
8.MyTest.java
package cn.zhang.test; import java.io.IOException;
import java.util.Date;
import java.util.List; import org.junit.Before;
import org.junit.Test; import cn.zhang.dao.StudentDao;
import cn.zhang.dao.impl.StudentDaoImpl;
import cn.zhang.entity.Student; public class MyTest { StudentDao dao;
@Before
public void initData() throws IOException{
dao=new StudentDaoImpl();
} /**
* 模糊查询
* @throws IOException
*/
@Test
public void findStudentByName() throws IOException{
List<Student> list = dao.findStudntByName("呵");
for (Student student : list) {
System.out.println("编号: "+student.getStuno()+"姓名:"+student.getStuname());
} } /**
* 查询所有学生
* @throws IOException
*/
@Test
public void findAll() throws IOException{
List<Student> list = dao.findAll();
for (Student student : list) {
System.out.println("编号: "+student.getStuno()+"姓名:"+student.getStuname());
} } /**
* 删除学生
* @throws IOException
*/ @Test
public void delStudent() throws IOException{
dao.delStu(2);
System.out.println("成功!");
} /**
* 添加学生
* @throws IOException
*/
@Test
public void testAdd() throws IOException{
Student stu=new Student();
stu.setStuname("呵呵");
stu.setStuage(21);
stu.setStudate(new Date());
StudentDao dao=new StudentDaoImpl();
dao.add(stu);
} }
9.log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=debug, stdout
mybatis入门的更多相关文章
- MyBatis1:MyBatis入门
MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...
- mybatis入门基础(二)----原始dao的开发和mapper代理开发
承接上一篇 mybatis入门基础(一) 看过上一篇的朋友,肯定可以看出,里面的MybatisService中存在大量的重复代码,看起来不是很清楚,但第一次那样写,是为了解mybatis的执行步骤,先 ...
- MyBatis入门基础(一)
一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...
- MyBatis入门案例、增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
- mybatis入门_mybatis基本原理以及入门程序
一.传统jdbc存在的问题 1.创建数据库的连接存在大量的硬编码, 2.执行statement时存在硬编码. 3.频繁的开启和关闭数据库连接,会严重影响数据库的性能,浪费数据库的资源. 4.存在大量的 ...
- MyBatis入门学习教程-使用MyBatis对表执行CRUD操作
上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...
- MyBatis入门学习(二)
在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...
- MyBatis入门学习(一)
一.MyBatis入门简要介绍(百科) MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyB ...
- MyBatis入门案例 增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
- MyBatis入门(五)---延时加载、缓存
一.创建数据库 1.1.建立数据库 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.7.9-log : Database - mybatis ****** ...
随机推荐
- Google Chrome调试js入门
平常在开发过程中,经常会接触到前端页面.那么对于js的调试那可是家常便饭,不必多说.最近一直在用火狐的Firebug,但是不知道怎么的不好使了.网上找找说法,都说重新安装狐火浏览器就可以了,但是我安装 ...
- [大数据之Spark]——Transformations转换入门经典实例
Spark相比于Mapreduce的一大优势就是提供了很多的方法,可以直接使用:另一个优势就是执行速度快,这要得益于DAG的调度,想要理解这个调度规则,还要理解函数之间的依赖关系. 本篇就着重描述下S ...
- 初识Jsp,JavaBean,Servlet以及一个简单mvc模式的登录界面
1:JSP JSP的基本语法:指令标识page,include,taglib;page指令标识常用的属性包含Language用来定义要使用的脚本语言:contentType定义JSP字符的编码和页面响 ...
- json、javaBean、xml互转的几种工具介绍
json.javaBean.xml互转的几种工具介绍 转载至:http://blog.csdn.net/sdyy321/article/details/7024236 工作中经常要用到Json.Jav ...
- 深入理解javascript描述元素内容的5个属性
× 目录 [1]innerHTML [2]outerHTML [3]innerText[4]outerText[5]textContent 前面的话 <p>This is a <i& ...
- Linux笔记之——Linux关机命令详解(转)
原文连接:http://www.jb51.net/os/RedHat/1334.html 在linux下一些常用的关机/重启命令有shutdown.halt.reboot.及init,它们都可以达到重 ...
- 关于table的一些记录
HTML有10个表格相关标签 <caption> 表格的大标题,该标记可以出现在<table> 之间的任意位置.它对于搜索引擎的机器人记录信息十分重要.参数有align.val ...
- C++面向对象
此博文仅作为C++考研专业课的复习内容. 面向对象 构造函数 在对象被创建的时候将自动调用. 复制构造函数 形参是本类对象的引用.其作用是使用一个已经存在的对象,去初始化一个同类的新对象. 复制构造函 ...
- MongoDB的CRUD操作
1. 前言 在上一篇文章中,我们介绍了MongoDB.现在,我们来看下如何在MongoDB中进行常规的CRUD操作.毕竟,作为一个存储系统,它的基本功能就是对数据进行增删改查操作. MongoDB中的 ...
- spring笔记--事务管理之声明式事务
事务简介: 事务管理是企业级应用开发中必不可少的技术,主要用来确保数据的完整性和一致性, 事务:就是一系列动作,它们被当作一个独立的工作单元,这些动作要么全部完成,要么全部不起作用. Spring中使 ...