Mybatis
Mybatis搭建与使用
1. pom文件中的依赖
<!-- mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 数据池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
2. 修改配置文件
这里使用 yml 格式的配置文件
# 数据库连接配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
password: qwer1234
url: jdbc:mysql://localhost:3306/project_manager?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
# mybatis 配置
mybatis:
type-aliases-package: mybatis.pojo
mapper-locations: classpath:/mapper/*.xml
3. 定义Java 对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String others;
}
4. 定义mapper接口
@Mapper
public interface UserMapper {
public List<User> selectAllUsers();
public List<User> selectLimit(Map<String, Object> map);
public void insertUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
public User selectUserById(Integer id);
public User selectUserByName(String name);
}
5. 在xml文件中实现
<?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="mybatis.mapper.UserMapper">
<select id="selectAllUsers" resultType="mybatis.pojo.User">
select *
from pm_user;
</select>
<select id="selectLimit" parameterType="map" resultType="mybatis.pojo.User">
select *
from pm_user limit #{startIndex}, #{pageSize};
</select>
<select id="selectUserById" parameterType="integer" resultType="mybatis.pojo.User">
select id, name, others
from pm_user
where id = #{id}
</select>
<select id="selectUserByName" parameterType="string" resultType="mybatis.pojo.User">
select id, name, others
from pm_user
where name = #{name}
</select>
<insert id="insertUser" parameterType="mybatis.pojo.User">
insert into pm_user (id, name, password, others)
values (#{id}, #{name}, #{password}, #{others})
</insert>
<update id="updateUser" parameterType="mybatis.pojo.User">
update pm_user set
password = #{password},
others = #{others}
where id = #{id}
</update>
<delete id="deleteUser" parameterType="mybatis.pojo.User">
delete
from pm_user
<where>
<if test="id != null">
id = #{id}
</if>
<if test="name != null">
name = #{name}
</if>
</where>
</delete>
</mapper>
6. 创建 Service层
创建接口文件
public interface UserService {
public List<User> selectAllUsers();
public List<User> selectLimit(Map<String, Object> map);
public void insertUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
public User selectUserById(Integer id);
public User selectUserByName(String name);
}
对定义的接口进行实现,这里为了演示,没有业务相关操作
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectAllUsers() {
return userMapper.selectAllUsers();
}
@Override
public List<User> selectLimit(Map<String, Object> map) {
return userMapper.selectLimit(map);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public void deleteUser(User user) {
userMapper.deleteUser(user);
}
@Override
public User selectUserById(Integer id) {
return userMapper.selectUserById(id);
}
@Override
public User selectUserByName(String name) {
return userMapper.selectUserByName(name);
}
@Override
public void insertUser(User user) {
userMapper.insertUser(user);
}
}
7. 创建一个Controller测试
可以搞一个测试类测试,应该会更方便。
@RestController
@RequestMapping("pm")
public class Main {
@Autowired
private UserService userService;
@GetMapping("/test")
public String test() {
// 查询所有用户
System.out.println("查询所有用户");
System.out.println(userService.selectAllUsers());
// 分页查询
System.out.println("分页查询");
Map<String, Object> map = new HashMap<>();
map.put("startIndex", 0);
map.put("pageSize", 3);
System.out.println(userService.selectLimit(map));
// 创建用户
User user = new User();
user.setId(null);
user.setName("000");
user.setOthers(null);
user.setPassword("123");
userService.insertUser(user);
System.out.println("创建用户");
System.out.println(user);
// 更新用户
user.setId(1);
user.setPassword("999");
user.setOthers("update");
userService.updateUser(user);
System.out.println("更新用户");
System.out.println(user);
// 删除用户
user.setName("asd");
user.setId(null);
userService.deleteUser(user);
System.out.println("根据用户名删除");
System.out.println(user);
user.setId(4);
user.setName(null);
userService.deleteUser(user);
System.out.println("根据id删除");
System.out.println(user);
// 根据用户名查询
System.out.println(userService.selectUserByName("qwe"));
// 根据 id 查询
System.out.println(userService.selectUserById(12));
return "OK";
}
}
Mybatis-plus
1. 添加项目依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
2. 修改配置文件
只需要配置数据库的相关内容,Mybatisplus不需要额外的配置信息。
3. 添加 mapperscan
注解
在项目主文件*Application.java
中添加@MapperScan()
注解
4. 定义Java对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String others;
}
5. 定义mapper接口
由于使用了 MybatisPlus,这步变得非常简单,可以直接继承 官方提供的内容即可。
public interface UserMapper extends BaseMapper<User>
6. 定义Service层
由于使用了MybatisPlus,这里就可以选择:
-
如果官方提供的Service层接口可以满足业务需要,就可以直接使用官方的接口。
-
如果官方提供的接口不满足业务需要:
- 可以在官方Service接口的基础上,做操作。
- 可以自己根据mapper层的官方接口实现Service层的逻辑。
这里就简单的调用下官方接口,自己做一个简单判断
public interface UserService extends IService<User> {
}
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public boolean save(User entity) {
log.debug("check user id: {}", entity.getId());
if (entity.getId()== null) {
return false;
}
return super.save(entity);
}
}
7. 测试下
@Test
void selectLimit() {
Page<User> page = new Page<>(0, 3);
// page.setSize(2);
// page.setCurrent(0);
Page<User> page1 = userService.page(page);
List<User> records = page1.getRecords();
System.out.println(records);
}
8. 分页查询配置
就简单的试了这个功能,把分页查询需要配置的写一下。
要实现分页查询的功能,需要在代码中写一个 配置类 , 里面创建一个拦截器。
这样就可以实现分页查询了…
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
Tk-Mybatis (使用了 PageHelper)
1. 添加项目依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.3</version>
</dependency>
2. 修改配置文件
# data
spring:
datasource:
url: jdbc:mysql://localhost:3306/project_manager?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
username: root
password: 'root'
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: tkmybatis.pojo
# page helper 配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
3. 添加 MapperScan
注解
在项目主文件*Application.java
中添加@MapperScan()
注解
4. 定义java对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String others;
}
5. 定义mapper接口
接口定义变得比较简单,tk-mybatis中已经封装了大部分的基础功能。
public interface UserMapper extends Mapper<User>, MySqlMapper<User>, RowBoundsMapper<User> {
}
6. 定义Service层
这个…就不搞了
7. 测试下(使用PageHelper实现下分页)
@Test
void select() {
// Example example = new Example(User.class);
// example.createCriteria().andBetween("id", 1, 1000);
// example.createCriteria().andEqualTo("id", "1");
PageHelper.startPage(1, 2);
List<User> users = userMapper.selectAll();
// List<User> users = userMapper.selectByExample(example);
PageInfo pageInfo = new PageInfo(users);
System.out.println("分页查询");
System.out.println(pageInfo.isHasNextPage());
pageInfo.setNextPage(2);
System.out.println(pageInfo.getList());
}