说明
在mybatis中使用注解开发可以简化mapper.xml文件的配置
使用方法
- 编写操作数据库的接口,写方法
- 在这些方法上面直接写注解
代码实例
public interface IBossMapper {
//1.查询所有的boss
@Select("select * from boss")
public List<Boss> allBoss();
//2.以bid查询boss
@Select("select * from boss where bid=#{bid}")
public Boss selByBid(int sid);
//3.插入一个boss
@Insert("insert into boss values(#{bid},#{bname})")
public void insert(Boss boss);
//4.以bid删除boss
@Delete("delete from boss where bid=#{bid}")
public void deleteByBid(int bid);
//5.以bid更新boss的bname
@Update("update boss set bname=#{bname} where bid=#{bid}")
public void updateBname(Boss boss);
//------------------------------注解实现一对一、一对多等关系---------------------------------
//一对一:以丈夫id找到丈夫及妻子
@Select("select * from husband where hid=#{hid}") //hid hname wid(wife)
//相当于resultMap
@Results({
//主键列
@Result(id=true,column="hid",property="hid"),
@Result(column="hname",property="hname"),
@Result(column="wid",property="wife",one=@One(
select = "selectWifeByWid"
))
})
public Husband selectHusbandByHid(int hid);
//以wid找到wife
@Select("select * from wife where wid=#{wid}")
public Wife selectWifeByWid(int wid);
//一对多
//以班级id,找到该班级及所有的学生
@Select("select * from clazz") //cid cname
@Results({
@Result(id=true,column="cid",property="cid"),
@Result(column="cname",property="cname"),
@Result(column="cid",property="students",many=@Many(
select="selectStudentsByCid",
fetchType=FetchType.LAZY //指定获取的类型为懒加载
))
})
public List<Clazz> allClazz();
//通过cid找到学生
@Select("select * from student where cid=#{cid}")
public List<Student> selectStudentsByCid(int cid);
//多对一:查询出所有的学生及学生所在的班级
@Select("select * from student")
@Results({
@Result(id=true,column="sid",property="sid"),
@Result(column="sname",property="sname"),
@Result(column="cid",property="clazz",one=@One(
select="selectClazzByCid"
))
})
public List<Student> allStudent();
@Select("select * from clazz where cid=#{cid}") //cid cname
public Clazz selectClazzByCid(int cid);
//多对多:以bid找到boss及其下的company
@Select("select * from boss where bid=#{bid}")
@Results({
@Result(id=true,column="bid",property="bid"),
@Result(column="bname",property="bname"),
@Result(column="bid",property="companies",many=@Many(
select="seleceCompaniesByBid"
))
})
public Boss selectBossByBid(int bid);
@Select("select * from boss_company bc,company c where bc.bid=#{bid} and bc.cid=c.cid")
@Results({
@Result(id=true,column="cid",property="cid"),
@Result(column="cname",property="cname")
})
public List<Company> seleceCompaniesByBid(int bid);
}
复制代码
使用:
public class Base {
public static void main(String[] args) {
SqlSession session = MyBatisUtil.getSession();
IBossMapper mapper = session.getMapper(IBossMapper.class);
System.out.println(mapper.selectBossByBid(1001));
session.commit();
}
}
复制代码