通用Mapper:可以实现自动拼接sql语句;所有的mapper都不需要编写任何方法也就是不用编写sql语句。可以提高开发效率。
1.添加启动器依赖
2.改造UserMapper继承Mapper<User>
import com.itheima.pojo.User; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }
3.修改启动引导类Application中的Mapper扫描注解
应该是引入
但是要注意这里的@MapperScan扫描注解一定要修改为通用mapper的扫描注解
4.修改User实体类添加jpa注解
@Data @Table(name = "tb_user") public class User { @Id //主键回填 @KeySql(useGeneratedKeys = true) private Long id; //user_name --> userName private String userName; private String password; private String name; private Integer age; private Integer sex; private Date birthday; private String note; private Date created; private Date updated; }
由于我安装了lombok插件,所以没有写Getter,Setter,toString等方法,只是使用了注解@Data,同时类上面的@Table注解是为了和数据库中的表对应。
5.改造UserService实现业务功能
@Service public class UserService { @Autowired private UserMapper userMapper; //根据id查询 public User queryById(Long id){ return userMapper.selectByPrimaryKey(id); } }
6.编写HelloController类中的相关方法
@RestController public class HelloController { @Autowired private UserService userService; @GetMapping("/user/{id}") public User queryById(@PathVariable Long id){ return userService.queryById(id); } @GetMapping("hello") public String hello(){ return "Hello Springboot"; } }
最后再用浏览器测试一下是否成功。