先看看目录结构:
Employee、dbconfig.properties、mybatis——config.xml在之前已经有了,此处不加描述。
主要看Main操作,Employee.xml,EmployeeMapper接口这三个。
Main函数。
public static void select(SqlSessionFactory sqlSessionFactory){
SqlSession openSession= null;
try {
openSession = sqlSessionFactory.openSession();
EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmployeeById(2);
System.out.println(employee);
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession.close();
}
}
public static void add(SqlSessionFactory sqlSessionFactory){
SqlSession openSession= null;
try {
openSession = sqlSessionFactory.openSession();
EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee(null,"ff","2222222","1");
mapper.addEmp(employee);
openSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession.close();
}
}
public static void delete(SqlSessionFactory sqlSessionFactory){
SqlSession openSession= null;
try {
openSession = sqlSessionFactory.openSession();
EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee(1,"ff","2222222","1");
mapper.deleteEmpById(4);
openSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession.close();
}
}
public static void updata(SqlSessionFactory sqlSessionFactory){
SqlSession openSession= null;
try {
openSession = sqlSessionFactory.openSession();
EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee(1,"ff","2222222","1");
mapper.updateEmpById(employee);
openSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
openSession.close();
}
}
当参数不止一个时:
在Mapper接口里面:
Employee getEmployee(@Param("id") Integer id, @Param("name") String name);
POJO:或者像上面的例子,当多个参数刚好都是业务逻辑的数据模型时,可以直接传入一个类对象,在xml配置文件直接用#{属性名}取出值
Map: 如果多个参数不是业务逻辑模型中的数据,我们可以传入Map
#{key}取出map的值。(参数类型不同时,可以直接将Map泛华为<String, Object>)(不建议使用)
@param注解类型
Map类型:传入参数是map,返回类型mybatis也可以说是map。只需要将xml的resultType参数改成map即可。
返回值如果不止一个,,那么用List<emlpoyee> 链表封装
当数据库主键自增时,插入数据的时候,可以获取到自增主键的值,做以下修改。
在取参数时有#{}和${}两种进行取值,
#{}:以预编译的形式,将参数设置到sql语句中,防止sql注入。即只能传输数据查询的参数
${}:取出的值直接拼接在sql语句当中;会有安全问题。
大多数情况下,我们取参数应该用#{};
原生JDBC不支持占位符的地方我们就应该使用#{}
比如分表、排序。。
select * from ${year}_salary where XXX;(直接拼接成所要查询的表)
select * from employee order by ${name}