Mybatis Plus的基础使用

  • 为简化开发而生

1.实体类的定义

1
2
3
4
5
6
7
8
9
10
11
@Data
@TableName("userswork") // 映射表
public class Userwork {
@TableId(type = IdType.AUTO) // 主键策略
private int id;
private int workid;
private int userid;

@TableField(exist = false) // 列策略:是否对应表属性,查询时是否返回结果....
private int other;
}

2.Mapper的书写(多表查询使用SQL拼接)

  • 继承BaseMapper实现基本的CURD功能
  • 简单语句可以使用自带的CRUD
  • 复杂语句也可以使用sql语句拼接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package kid1999.upload.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import kid1999.upload.model.HomeWork;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface homeworkMapper extends BaseMapper<HomeWork> {

@Select("select * from homework where title = #{title} and id in (select workid from userswork where userid = #{userId})")
HomeWork findHKByTitleAndUserID(String title,int userId);

@Insert("insert into homework(title, infomation, createtime, endtime, type, addr) values (#{title},#{infomation} ,#{createtime} ,#{endtime} ,#{type} ,#{addr} )")
void addHomeWork(HomeWork homeWork);

@Select("select * from homework where id in (select workid from userswork where userid = #{userid} ) ")
List<HomeWork> findByUserId(Integer userid);

@Select("select addr from homework where id = (select workid from student where student.id = #{uid})")
String findaddrBySid(int uid);


@Select("select * from homework where title = #{title} and id in (select workid from userwork where userid = #{userId})")
HomeWork findHKByTitle(String title,int userId);
}

3.在Service中实现一些简单的单表CRUD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package kid1999.upload.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import kid1999.upload.mapper.userMapper;
import kid1999.upload.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;



@Service
public class userService {

@Autowired
private userMapper userMapper;

// 简单查询使用 QueryWrapper
public User findUserByName(String name) {
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name",name);
return userMapper.selectOne(wrapper);
}

// 增加 使用自带的 insert
public int addUser(User user) {
return userMapper.insert(user);
}

public User login(User user) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name",user.getName())
.eq("password",user.getPassword());
return userMapper.selectOne(wrapper);
}

// 更新student
public int updateStudent(Student student) {
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.eq("id",student.getId())
.eq("name",student.getName());
return studentMapper.update(student,wrapper);
}
}

后续再修订 。。。。