作用:可以将单表的增删改查操作省去
一、添加依赖
<!--mybatis通用mapper的依赖--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.2.3</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </exclusion> </exclusions> </dependency>
二、让mapper接口继承Mapper<T>接口
注意:是该包的Mapper接口(package tk.mybatis.mapper.common),其泛型是对应的实体类
package com.atguigu.gmall.user.mapper;
import com.atguigu.gmall.user.domain.Users;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface UserMapper extends Mapper<Users> {
//无需写方法,直接在service实现类调用方法
}
三、在实现类调用方法
package com.atguigu.gmall.user.service.impl;
import com.atguigu.gmall.user.domain.Users;
import com.atguigu.gmall.user.mapper.UserMapper;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
public List<Users> getAllUser(){
//该selectAll方法是通用mapper制定好的,直接调用。其中还有好多方法
List<Users> userList = userMapper.selectAll();
return userList;
}
}
四、在实体类中添加注解如下
@Id指定主键
@GenneratedValue(strategy=GennerationType.IDENTITY)指定主键返回策略
package com.atguigu.gmall.user.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Users {
@Id//指定主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//指定主键返回策略
private Integer id;
private String name;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
五、在启动类上配置通用mapper的扫描器
@MapperScan(basePackages="com.atguigu.gmall.user.mapper")注意是该包下的(tk.mybatis.spring.annotation.MapperScan)
package com.atguigu.gmall.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
//@MapperScan(basePackages = "com.atguigu.gmall.user.mapper")
@MapperScan(basePackages = "com.atguigu.gmall.user.mapper")
public class GmallUser01Application {
public static void main(String[] args) {
SpringApplication.run(GmallUser01Application.class, args);
}
}
浙公网安备 33010602011771号