mybatis笔记(三)

注解开发

1.注解在接口上使用

1
2
@Select("select * from student")
List<Student> getStudents();

2.需要在核心配置文件中绑定接口

1
2
3
4
5
<mappers>
<!-- <mapper resource="cn/demomybatis/dao/StudentDao.xml"/>-->
<!-- <mapper class="cn.demomybatis.dao.StudentDao"/>-->
<package name="cn.demomybatis.dao"/>
</mappers>

本质:反射机制实现

底层:动态代理!

MyBatis详细执行流程

CRUD

我们可以在创建工具类的时候实现自动提交事务!

1
2
3
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}

编写接口,增加注释

1
2
3
4
5
6
7
8
9
10
//方法存在多个参数,所有参数前面必须加上@Param注解
@Select("select * from student where id = #{id}")
Student getStudentById1(@Param("id") int id);

@Insert("insert into student(id,name,age,phone) values(#{id},#{name},#{age},#{phone})")
int addStudent1(Student student);


@Update("update student set name=#{name},age=#{age},phone=#{phone} where id = #{id}")
int updateStudent1(Student student);

关于@Param注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议加上
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!

Lombok

使用步骤:

1.在IDEA中安装Lombok插件

2.在项目导入Lombok的jar包

3.

1
2
3
@Data:生成无参构造,get,set,toString,hashcode,equals
@AllArgsConstructor 有参构造方法
@NoArgsConstructor 无参构造方法

多对一处理

按照插叙嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的tid,寻找对应的老师! 子查询-->

<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>


<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>

按照结果嵌套处理

1
2
3
4
5
6
7
8
9
10
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>

一对多处理

同理

小结

1.关联 - association 【多对一】

2.集合 - collection 【一对多】

3.javaTape:用来指定实体类中属性的类型

4.ofType:用来指定映射到List或者集合中的实体类类型,泛型中的约束类型

评论