mybatis详解
1、设置结果映射
mybatis需要设置结果映射resultMap来一一对应实体属性和表属性
这是为了解决实体属性名和表属性名不一致导致的问题的’
一般在实际项目中都需要设置结果映射,单纯的resultType几乎不可见
1.1映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="configure.mapper.EmpMapper">
<!--设置属性映射
resultMap是组装从数据库表中查询出来的数据对应实体
type:实体的数据类型
id:只有一个
column:表属性名
property:实体属性名
-->
<resultMap id="baseResultMap" type="model.Emp">
<id column="person_id" property="personId"/>
<result property="name" column="name"/>
<!--不用映射的属性也要写出来-->
<result property="gender" column="gender"/>
<result property="birthday" column="birthday"/>
<result property="personAddr" column="person_addr"/>
</resultMap>
<select id="selectEmp" parameterType="java.lang.Integer" resultMap="baseResultMap">
select *from person p where p.person_id=#{identity }
</select>
</mapper>
1.2实体类
public class Emp {
private Integer personId;
private String name;
private Integer gender;
private String personAddr;
private Date birthday;
@Override
public String toString() {
return "Emp{" +
"personId=" + personId +
", name='" + name + '\'' +
", gender=" + gender +
", personAddr='" + personAddr + '\'' +
", birthday=" + birthday +
'}';
}
public Integer getPersonId() {
return personId;
}
public void setPersonId(Integer personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getPersonAddr() {
return personAddr;
}
public void setPersonAddr(String personAddr) {
this.personAddr = personAddr;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
1.3测试类
@Test
public void testPerson() {
SqlSession session = sf.openSession();
try {
Emp emp =session.selectOne("configure.mapper.EmpMapper.selectEmp",1);
System.out.println(emp);
}finally {
session.close();
}
}
2.mybatis简单查询
2.1查询所有数据
映射文件
<select id="selectAllEmp" resultMap="baseResultMap">
select *from person
</select>
测试类
@Test
public void selectPerson() {
SqlSession session = sf.openSession();
try {
List<Emp> empList = session.selectList("configure.mapper.EmpMapper.selectAllEmp");
for (Emp emp : empList) {
System.out.println(emp);
}
}finally {
session.close();
}
}
2.2指定条件下的查询
第一种方式
映射文件
设置查询类来作为查询参数,类型转换:<![CDATA[]]>
<!--
第一种方法:传递查询对象
QueryCondition qc= new QueryCondition();
qc.setGender{1};
qc.setBirthday{new date()}
#{}通过查询对象的get方法进行取值,内容直接填属性名就可以了
-->
<select id="selectEmpByparams" parameterType="model.QueryCondition" resultMap="baseResultMap">
<![CDATA[
select * from person p where p.gender=#{gender} and p.birthday<#{birthday}
]]>
</select>
测试类
@Test
public void selectPa() {
SqlSession session = sf.openSession();
try {
//设置qc这个参数
QueryCondition qc = new QueryCondition();
qc.setGender(1);
qc.setBirthday(new Date());
List<Emp> empList = session.selectList("configure.mapper.EmpMapper.selectEmpByparams",qc);
for (Emp emp : empList) {
System.out.println(emp);
}
}finally {
session.close();
}
}
第二种方式
使用map集合作为查询参数进行查询
映射文件
<!--
第二种方法使用map,多个参数的传递也可以使用map集合
Map<String,Object> map=new HashMap<>();
map.put("gender",1);
map.put("birthday",new Date());
#{}中的内容和map中的key要一致
-->
<select id="selectEmpByparam" parameterType="java.util.Map" resultMap="baseResultMap">
<![CDATA[
select * from person p where p.gender=#{gender} and p.birthday<#{birthday}
]]>
</select>
测试类
@Test
public void selectMap() {
SqlSession session = sf.openSession();
try {
//设置map这个参数
Map<String,Object> map=new HashMap<>();
map.put("gender",1);
map.put("birthday",new Date());
List<Emp> empList = session.selectList("configure.mapper.EmpMapper.selectEmpByparams",map);
for (Emp emp : empList) {
System.out.println(emp);
}
}finally {
session.close();
}
}
2.3模糊查询
映射文件
注意模糊查询的写法 like '%${name}%'
${}非预编译,${}中的内容必须从map或者查询对象中获得
<select id="selectEmpByName" parameterType="java.util.Map" resultMap="baseResultMap">
select * from person p where p.name like '%${name}%';
</select>
测试类
@Test
public void selectLike() {
SqlSession session = sf.openSession();
try {
//设置map这个参数
Map<String,Object> map=new HashMap<>();
map.put("name","政");
List<Emp> empList = session.selectList("configure.mapper.EmpMapper.selectEmpByName",map);
for (Emp emp : empList) {
System.out.println(emp);
}
}finally {
session.close();
}
}
3.mybatis的insert保存
3.1单表保存
映射文件
<insert id="insert" parameterType="model.Emp">
insert into person(name, gender, person_addr, birthday) values (#{name },#{gender},
#{personAddr},#{birthday}
)
</insert>
测试类
@Test
public void insert() {
SqlSession session = sf.openSession();
Emp emp = new Emp();
emp.setName("庄周");
emp.setGender(1);
emp.setPersonAddr("稷下学宫");
emp.setBirthday(new Date());
try {
int insert = session.insert("configure.mapper.EmpMapper.insert", emp);
//对数据的操作凡事增,删,逃不过事务,都要进行事务的提交(可提交读)
session.commit();
System.out.println(insert);
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally {
session.close();
}
}
3.2关联表的保存
/*
如下对于order表和orderDetail表二者首先是一对多关系
会在orderDetail表中产生一个外键orderId,
如果保存了order,则因为无法知道orderId无法保存orderDetail
* orderDao orderDao
* orderDetailDao orderDetailDao
*
* public void saveOrder(Order order,OrderDetail od){
* //返回订单编号则可以保存订单明细
* orderDao.save(order);
* od.setOrderId(order.getOrderId());
* //此时就可以保存订单明细
* orderDao.save(od);
* }
* */
映射文件
<insert id="insert" parameterType="model.Emp">
/*
keyProperty:对于要返回的主键的接收
order:插入sql和生成主键的顺序,mysql是after
resultType:主键返回的数据类型
生成主键的sql:LAST_INSERT_ID()
*/
<selectKey keyProperty="personId" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into person(name, gender, person_addr, birthday) values (#{name },#{gender},
#{personAddr},#{birthday}
)
</insert>
测试类
/*
如下对于order表和orderDetail表二者首先是一对多关系
会在orderDetail表中产生一个外键orderId,
如果保存了order,则因为无法知道orderId无法保存orderDetail
* orderDao orderDao
* orderDetailDao orderDetailDao
*
* public void saveOrder(Order order,OrderDetail od){
* //返回订单编号则可以保存订单明细
* orderDao.save(order);
* od.setOrderId(order.getOrderId());
* //此时就可以保存订单明细
* orderDao.save(od);
* }
* */
@Test
public void insert1() {
SqlSession session = sf.openSession();
Emp emp = new Emp();
emp.setName("芈月");
emp.setGender(0);
emp.setPersonAddr("秦王宫");
emp.setBirthday(new Date());
try {
int insert = session.insert("configure.mapper.EmpMapper.insert", emp);
//对数据的操作凡事增,删,逃不过事务
session.commit();
System.out.println(insert);
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally {
session.close();
}
}
4.mybatis的update修改
映射文件
<update id="updateEmp" parameterType="model.Emp">
update person p set p.name =#{name},
p.gender=#{gender},
p.person_addr=#{personAddr},
p.birthday=#{birthday}
where p.person_id=#{personId}
</update>
测试类
@Test
public void update() {
SqlSession session = sf.openSession();
Emp emp = new Emp();
emp.setPersonId(1);
emp.setGender(1);
emp.setBirthday(new Date());
emp.setName("阿珂");
emp.setPersonAddr("打野区");
try {
session.update("configure.mapper.EmpMapper.updateEmp",emp);
session.commit();
}finally {
session.close();
}
}
5.mybatis的delete删除
映射文件
<delete id="deleteEmp" parameterType="java.lang.Integer">
delete from person where person_id=#{id}
</delete>
测试类
@Test
public void delete() {
SqlSession session = sf.openSession();
try {
int delete = session.delete("configure.mapper.EmpMapper.deleteEmp", 10);
session.commit();
System.out.println(delete);
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally {
session.close();
}
}