Mybatis-Plus使用AR(Active Record)(三)

1)先构建项目,具体看上2章的操作

spring与Mybatis-plus集成https://blog.csdn.net/qq_37431224/article/details/103976970

springboot与Mybatis-plus集成https://blog.csdn.net/qq_37431224/article/details/104000588

2)在user实体类继承Model

@Data
//防止基础Model与Data冲突,使Model的方法被Data覆盖掉
@EqualsAndHashCode(callSuper=false)
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value="sys_user")//建立User.class和数据库表sys_user的关系
//继承Model可以实现AR操作
public class User extends Model<User> implements Serializable{
	
   private static final long serialVersionUID=1L;
   
   //@TableId(value="userId")//代表他是主键,且value为表中的名称
   private Integer id;
   //@TableField(value="user_name")
   private String name;
   private String address;
   private Date birth;
   
   //如果数据库表没有该字段时,orm映射可以忽略该字段,否则映射时报错
   @TableField(exist=false)
   private String sex;
}

3)加载Page的Bean

方式1:直接在Config类配置Bean

@SpringBootApplication
@MapperScan(basePackages={"com.demo.mapper"})
public class Application {
	public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
	}
	
	@Bean
	public PaginationInterceptor paginationInterceptor(){
		return new PaginationInterceptor();
	}
}

方式2:自定义Mybatis-plus的config类,配置page的Bean

@Configuration
//由于已经有Config配置对象,而@ConditionalOnClass则表示为该类为候选Config,在原Config查不到时会到这个Config查询
@ConditionalOnClass(value={PaginationInterceptor.class})
public class MybatisPlusConfig {

	@Bean
	public PaginationInterceptor paginationInterceptor(){
		return new PaginationInterceptor();
	}
}

4)编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
    @Autowired
    private UserMapper userMapper;
    
    @Test
    public void testAR(){
    	User user=new User();
    	user.setId(1);
    	user.selectById();
    	System.out.println(user);
    	user.setBirth(new Date());
    	user.updateById();
    	
    	//分页
    	IPage<User> page =new Page<User>(1,5);
    	user.selectPage(page, null);
    	List<User> users = page.getRecords();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37431224/article/details/104000793