文章目录
- 6.分页
- 6.1、使用Limit分页:
- 6.2、RowBounds
- 6.3、分页插件
- 7、使用注解开发
- 7.1、步骤
- 7.2、使用注解完成CRUD
- 8、Lombok
- 9、多对一处理
- 1.环境搭建
- 2.测试环境搭建
- 按照查询嵌套处理
- 按照结果嵌套处理
- 10.一对多处理
- 按照查询嵌套处理
- 按照结果嵌套处理
- 小结
6.分页
为什么 要分页?
- 减少数据的处理量
6.1、使用Limit分页:
语法:select * from user limit startindex,pagesize;
使用Mybatis实现分页,核心SQL
1.接口
//分页查询
List<User> getListByLimit(Map<String,Integer> map);
2.Mapper.xml
<select id="getListByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{start},#{size}
</select>
3.测试
@Test
public void getListByLimitTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("start",0);
map.put("size",4);
List<User> users = mapper.getListByLimit(map);
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
6.2、RowBounds
不再使用sql来实现分页
1.接口
//RowBounds分页
List<User> getUserByRowBounds();
2.Mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
3.测试
@Test
public void getUserByRowBoundsTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
//新建一个RoeBounds实例对象,参数与limit()一样
RowBounds rowBounds = new RowBounds(0, 3);
//通过java代码层面实现分页
List<User> users = sqlSession.selectList("com.cjp.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
6.3、分页插件
PageHelper
7、使用注解开发
7.1、步骤
1.声明接口
@Select("select * from user")
List<User> getUsers();
2.绑定注册
<mappers>
<mapper class="com.cjp.dao.UserMapper" />
</mappers>
3.测试
@Test
public void getUsersTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理!
7.2、使用注解完成CRUD
在编写Mybatis工具类时可以通过参数来设置自动提交事务,之后就不需要手动提交了:
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
1.接口
//通过ID查找用户
@Select("select * from user where id=#{id}")
//当有多个参数时,所有的参数必须加上注解
User getUserByID(@Param("id") int id);
//添加一个用户
@Insert("insert into user (id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
//删除一个用户
@Delete("delete from user where id=#{id}")
int delUser(@Param("id") int id);
//修改用户信息
@Update("update user set name=#{name} where id=#{id}")
int updateUser(@Param("name") String name,@Param("id") int id);
2.测试
@Test
public void getUserByIdTest() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserByID(1001);
System.out.println(user);
sqlSession.close();
}
@Test
public void insertUser() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(1009,"芭比Q","babiqle"));
sqlSession.close();
}
@Test
public void delUser() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(1009);
sqlSession.close();
}
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser("Handsome",1001);
sqlSession.close();
}
注意:我们要确保接口绑定注册到核心配置文件mybatis-config.xml中。
@Param()注解的使用
- 基本类型或者String 类型的参数,需要使用
- 引用类型不需要使用
- 如果只有一个基本类型的话,可以不使用,但建议使用
- 我们在SQL中引用的参数就是通过@Param中设置的参数名
8、Lombok
Lombok项目是一个java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。
使用步骤:
1.在IDEA中安装Lombok插件
2.在项目中导入Lombok的Jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
3.Lombok注解:
@Data,@getter,@setter,@NoArgsConstructor,@AllArgsConstructor,@ToString,@EqualsAndHashCode,@Slf4j,@Log4j
在实体类上加注解:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zeEMHeqU-1651929103489)(D:\Desktop\学习笔记\图片\image-20220507163212888.png)]
9、多对一处理
1.环境搭建
数据库:
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
2.测试环境搭建
1.导入Lombok
2.新建实体类Teacher、Student
package com.cjp.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.cjp.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
}
3.建立Mapper接口
4.建立Mapper接口对应的Mapper.xml文件
5.在核心配置文件中绑定注册我们的Mapper接口或者配置文件
6.测试
按照查询嵌套处理
<!--思路
1.查询所有学生的信息
2.根据查询出来的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentMap" >
select * from student;
</select>
<resultMap id="StudentMap" type="Student">
<result column="id" property="id"/>
<result column="name" property="name"/>
<!--复杂的属性我们需要单独处理,对象:association,集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{tid}
</select>
按照结果嵌套处理
<!--按照结果嵌套处理-->
<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>
10.一对多处理
比如一个老师教多个学生,对于老师而言就是一对多的关系
1.搭建环境
2.修改实体类
package com.cjp.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
package com.cjp.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudents" column="id"/>
</resultMap>
<select id="getStudents" resultType="Student">
select * from student where tid=#{id}
</select>
按照结果嵌套处理
<select id="getTeacher1" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
小结
1.关联 -association【多对一】
2.集合- collection【一对多】
3.JavaType ofType
JavaType:用来指定实体类中属性的类型
oftype:用来指定映射到List或者集合中的实体类类型,泛型中的约束类型!