Mybatis_映射文件
原创
©著作权归作者所有:来自51CTO博客作者959_1x的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录
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}
2.CRUD
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
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();
}
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,才可以生效
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();
}
这里由于上面的映射文件改的只是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();
}
5.获取自增的值
需要加上useGeneratedKeys属性和keyProperty的属性
insert into tbl_employ values (#{id}, #{last_name}, #{gender}, #{email})
6.多个参数@Param注解
加上@Param()注解
7.多个参数map
还可以封装在一个map集合中,可以直接取值id,name,不用取param