传递 pojo 包装对象
开发中通过 pojo 传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查 询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。 Pojo 类中包含 pojo。 需求:根据用户名查询用户信息,查询条件放到 QueryVo 的 user 属性中。
当parameterType的类型为对象 的时候name的值不能随便命名,必须与实体类的属性名相同
获取主键自增后的ID属性
test类
@Test
public void InsertEmployee() {
String resource = "mybatis-config.xml";//配置文件名
Reader reader = null; //读取配置文件的工具
SqlSession session = null;
try {
//使用MyBatis提供的Resources类加载mybatis的配置文件
reader = Resources.getResourceAsReader(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory =
new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
session = sessionFactory.openSession();
//创建实体对象,将它insert到数据库中
Employee e = new Employee();
e.setName("张三");
e.setBirthday(new Date());
e.setDept(2);
e.setSalary(9809F);
session.insert("EMPLOYEE.insertEmployee",e );
session.commit();//增删改要提交事务
//insert标签中设置keyProperty和useGeneratedKeys后才能看到值,否则是null
System.out.println(e .getId());
} catch (Exception ex) {
ex.printStackTrace();
session.rollback();//有异常事务回滚
} finally {//关闭资源
if (session != null) {
session.close();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
实体类
public class Employee {
private Integer id;
private String name;
private Date birthday;
private Integer dept;
private Float salary;
//getter/setter方法略
}
EmployeeMapper
<!--映射文件-->
<mapper namespace="EMPLOYEE">
<insert id="insertEmployee" parameterType="pojo.Employee" keyProperty="id" useGeneratedKeys="true">
insert into Employee(name,birthday,dept,salary) values(#{name},#{birthday},#{dept},#{salary})
</insert>
</mapper>
配置文件里添加
<mapper resource="dao/mapper/EmployeeMapper.xml"/>