Mybatis总结

来源:互联网 发布:everying软件缩略图 编辑:程序博客网 时间:2024/06/18 13:56

MyBatis框架:

原本是apache的开源项目iBatis,后来过度给了谷歌了,更名为MyBatis.
1.持久化的框架.Hibernate,内容过于庞大,学习成本高
2.方言,hql,最后还是被转换成sql,但是不灵活。mybatis和jdbc类似,就是书写sql语句.
3.所以mybatis的执行效率,略高
4.mybatis代码结构类似与jdbc,学习(上手)容易
5.sql语句和代码分离,更加符合面向对象的分层思想.

一、基本CRUD

1.加入jar包
mybatis-3.3.2.jar
2.src下加入数据库相关的配置文件
mybatis-config.xml
3.实体类(1.手写2.逆向工程(配置插件aa))
4.存放sql语句的文件.DeptMapper.xml
可以配置多个数据库
ThreadLocal aa

案例:

Mybatis_test1

步骤:
1>mybatis-config.xml
















2> DeptMapper.xml



insert into dept
(deptno,dname,loc)
values
(#{deptno},#{dname},#{loc})


delete from dept where deptno=#{deptno}


update dept set dname=#{dname},loc=#{loc}
where deptno=#{deptno}



select * from dept order by deptno desc

3>封装MySqlSession类,获得SqlSession对象

public class MySqlSession {
static InputStream in;
static SqlSessionFactory sf;
// ThreadLocal==妈妈的钱包
static {
try {
in = Resources.getResourceAsStream(“mybatis-config.xml”);
// 加载mybatis-config.xml
sf = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSessionFactory工厂
} catch (IOException e) {
e.printStackTrace();
}
}

public static SqlSession getSession() {
// 获得SqlSession对象
return sf.openSession();
}

}

4> DeptDao.java

//查询
public static void test1() {
List list = getSession().selectList(“crud.cha”);
// selectList(“crud.cha”)查询,crud.cha类名全路径,参数为id值。
for (Dept d : list) {
System.out.println(d.getDeptno() + “\t” + d.getDname() + “\t” + d.getLoc());
}
}

//添加
public static void test2(Dept d) {
SqlSession se = getSession();
// insert(“crud.tian”, d)添加,参数一为id,参数二为对象
se.insert(“crud.tian”, d);
// 需要事务支持
se.commit();
}

//修改
public static void test3(Dept d) {
SqlSession se = getSession();
// update(“crud.gai”, d) 修改
se.update(“crud.gai”, d);
se.commit();
}

//删除
public static void test4(int deptno) {
SqlSession se = getSession();
/*
* delete(“crud.shan”, deptno)
* 删除参数一为id,参数二为表的id
*/
se.delete(“crud.shan”, deptno);
se.commit();
}

二、resultMap标签
如果表中的字段(列)名称和java实体类属性的名称发生不一致.就需要这个标签来标注

Mybatis_test2

DeptMapper.xml:










insert into dept
(deptno,dname,loc)
values
(#{sundeptno},#{sundname},#{sunloc})




select * from dept order by deptno

DeptDao.java:

public static void test1() {
List list = getSession().selectList(“crud.cha”);
for (Dept d : list) {
// d.getSundeptno() 通过Dept对象的get方法取值
System.out.println(d.getSundeptno() + “\t” + d.getSundname() + “\t” + d.getSunloc());
}
}

三、sql标签
重复的sql语句片段,永远都会出现(包含重复的sql语句)

Mybatis_test3

DeptMapper.xml:



select * from dept order by deptno



desc

四、sql语句作为变量传入
内容当参数传入

Mybatis_test4

DeptMapper.xml:


select * from dept order by deptno ${x}

DeptDao.java:

public static void test1() {
Map

{id}


DeptDao.java:

public static void test1() {
Map

原创粉丝点击