文章目录


1.映射文件

XxxMapper.xml


PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">






insert into tbl_employ values (#{id}, #{last_name}, #{gender}, #{email})



update tbl_employ set last_name = #{last_name} where id = #{id}



delete from tbl_employ where id = #{id}


Mybatis_映射文件_sql

2.CRUD

    public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}

Mybatis_映射文件_mybatis_02

1.select

test.java

    @Test
public void test2()throws Exception{
SqlSession sqlSession = getSqlSessionFactory().openSession();
EmployMapperAnnocation mapper = sqlSession.getMapper(EmployMapperAnnocation.class);
Employee byId = mapper.getById(1);
System.out.println(byId);
sqlSession.close();
}

Mybatis_映射文件_sql_03

2.insert

test.java

    @Test
public void test3()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//无参的话需要手动提交事务
SqlSession openSession = sqlSessionFactory.openSession();

EmployMapper mapper = openSession.getMapper(EmployMapper.class);

Employee zjy = new Employee(null, "Zjy", "www.baidu.com", "0");

mapper.addEmploy(zjy);

openSession.commit();

openSession.close();

}

这里需要注意的是如果用工厂创建openSession无参的话,则需要手动提交commit,才可以生效
Mybatis_映射文件_mybatis_04

3.update

test.java

    @Test
public void test4()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
EmployMapper mapper = openSession.getMapper(EmployMapper.class);
mapper.updateEmploy(new Employee(1,"Zzz", "Zzz@QQ.com", "1"));
openSession.commit();
openSession.close();
}

Mybatis_映射文件_java_05
Mybatis_映射文件_java_06
这里由于上面的映射文件改的只是last_name所以后面的没有修改

4.delete

test.java

    @Test
public void test5()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
EmployMapper mapper = openSession.getMapper(EmployMapper.class);
mapper.deleteEmploy(1);
openSession.commit();
openSession.close();
}

Mybatis_映射文件_java_07
Mybatis_映射文件_java_08

5.获取自增的值

需要加上useGeneratedKeys属性和keyProperty的属性


insert into tbl_employ values (#{id}, #{last_name}, #{gender}, #{email})

Mybatis_映射文件_mybatis_09
Mybatis_映射文件_java_10
Mybatis_映射文件_mybatis_11

6.多个参数@Param注解

加上@Param()注解
Mybatis_映射文件_映射文件_12
Mybatis_映射文件_映射文件_13

Mybatis_映射文件_sql_14

Mybatis_映射文件_映射文件_15

7.多个参数map

还可以封装在一个map集合中,可以直接取值id,name,不用取param
Mybatis_映射文件_mybatis_16

Mybatis_映射文件_java_17
Mybatis_映射文件_sql_18

Mybatis_映射文件_映射文件_19