使用springboot整合mybatis,使用通用mapper和mapper分页插件,
1.数据库的tingint对应java是boolean类型。
导包<!--分页插件 -->,mybatis的springboot新建的时候选择了。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!--tkmybatis -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.4</version>
</dependency>
yml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone= UTC
username: root
password: 123456
mybatis:
type-aliases-package: com.zy.msgaliyun.entity
- 创建表
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(32) NOT NULL COMMENT '密码,加密存储',
`phone` varchar(20) DEFAULT NULL COMMENT '注册手机号',
`created` datetime NOT NULL COMMENT '创建时间',
`salt` varchar(32) NOT NULL COMMENT '密码加密的salt值',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COMMENT='用户表';
- 编写实体类
@Data
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Length(min = 4, max = 30, message = "用户名只能在4~30位之间")
private String username;// 用户名
@JsonIgnore
@Length(min = 6, max = 30, message = "密码只能在4~30位之间")
private String password;// 密码
@Pattern(regexp = "^1[35678]\\d{9}$", message = "手机号格式不正确")
private String phone;// 电话
private Date created;// 创建时间
@JsonIgnore 这是jackson的注解,表示不会把该字段序列化返回给前端。
@Column(name = "salt")
private String salt;// 密码的盐值
}
l @Table 标示数据库表名
l @Id 主键id,bigint类型
l @GeneratedValue(strategy = GenerationType.IDENTITY) 主键自增长,前提是数据库字段必须设置成autoincreament
/*
* 使用的是jpa的策略生成器
*JPA提供的四种标准用法为TABLE,SEQUENCE,IDENTITY,AUTO.
* TABLE:使用一个特定的数据库表格来保存主键。
* SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列
* IDENTITY:主键由数据库自动生成(主要是自动增长型)
* AUTO:主键由程序控制。
*/
l @Column 如果类字段和数据库字段名不一致,用这个指定数据库的字段名做映射。
l @Transient 表名该字段不是数据库的字段,不会和数据库发生映射。
3编写mapper,
public interface UserMapper extends Mapper<User> {
}
4.配置类开启mapper注解
@SpringBootApplication
@MapperScan("com.zy.msgaliyun.mapper")
public class MsgAliyunApplication {
public static void main(String[] args) {
SpringApplication.run(MsgAliyunApplication.class, args);
}
}
5.使用
@RestController
public class TestController {
@Autowired
UserMapper userMapper;
@GetMapping("/users")
public List<User> getAllUser(){
return userMapper.selectAll();
}
}
5通用mapper提供了很多简单的增删改查。
两种新增
//会有选择性的新增, 智能判断 brand里面有没有空的字段,有值,用这个值,没有值而使用数据库的默值
insertSelective(brand)
// 假如前端提交过来的 brand里面的数据是全的,用词方法
brandMapper.insert(brand);
简单查询
/**
* 根据实体中的属性值进行查询,查询条件使用等号
* @param record
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
List<T> select(T record);
/**
* 根据实体中的属性值进行查询,查询条件使用等号
* @param record
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
List<T> select(T record);
/**
* 查询全部结果
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
List<T> selectAll();
/**
* 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
* @param record
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
T selectOne(T record);
/**
* 根据实体中的属性查询总数,查询条件使用等号
* @param record
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
int selectCount(T record);
简单删除
Copy
/**
* 根据主键字段进行删除,方法参数必须包含完整的主键属性
* @param key
* @return
*/
@DeleteProvider(type = BaseDeleteProvider.class, method = "dynamicSQL")
int deleteByPrimaryKey(Object key);
/**
* 根据实体属性作为条件进行删除,查询条件使用等号
* @param record
* @return
*/
@DeleteProvider(type = BaseDeleteProvider.class, method = "dynamicSQL")
int delete(T record);
如何玩修改?
/**
* 根据主键更新属性不为null的值
* @param record
* @return
*/
@UpdateProvider(type = BaseUpdateProvider.class, method = "dynamicSQL")
int updateByPrimaryKeySelective(T record);
看到这个方法有没有觉得很爽? 它根据主键,修改不为null的属性,意思就是说,我们把不需要修改的地方设置为null就好了
,这样看,前面需要我们一顿整,整啥呢? 结合实际的业务逻辑,把前端给交过来的数据最新的数据放到我们的bean中直接修改,把不需要修改的属性设置为null,有属性可能需要直接删除,有的属性可能要去别的表中查询(别忘了加上事务 @Transactional )
/**
* 根据主键更新实体全部字段,null值会被更新
* @param record
* @return
*/
@UpdateProvider(type = BaseUpdateProvider.class, method = "dynamicSQL")
int updateByPrimaryKey(T record);
这个方法和上面的神似
二 .分页,过滤(模糊查询),搜索#
API
Copy
mapper.selectByExample(example)
参照下面原生的sql.拼接查询条件
Copy
select * from 表名
where name like '% X %' or letter== 'x'
order by id desc
逻辑
public VO queryBrandByPage(Integer page, String key, Integer rows, String sortBy, Boolean desc) {
//分页 -- 使用分页助手,在我们真正查询之前,调用这个下面的方法,开启分页查询,他很智能,会用mybatis的拦截器
// 对接下来要执行查询的sql进行拦截,自动的在其后面拼接 limit语句
PageHelper.startPage(page,rows); //当前页码,每页显示的数目
//过滤 --key (StringUtils用的是comment lang3 下面的)
// 过滤条件,key是前端用户传递进来的,可能仅仅是一个 小米, 也可能是 小 --- 模糊查询
/* select * from tb_brand
where name like '% X %' or letter== 'x'
order by id desc
*/
Example example = new Example(Brand.class);
if(StringUtils.isNotBlank(key)){ //不为空,过滤
example.createCriteria().orLike("name","%"+key+"%").andEqualTo("letter",key.toUpperCase());
}
//排序
if(StringUtils.isNotBlank(sortBy)) { //传递进来的排序不为空,设置我们的排序条件
example.orderBy("age").desc();//排序
}
//查询 获取到list ,其实是 当前页的数据 page对象
List<Brand> list = brandMapper.selectByExample(example);
if (CollectionUtils.isEmpty(list)){
throw new Exception ;
}
// 解析List
PageInfo<Brand> pageInfo = new PageInfo<>(list);
return new PageResult<Brand>(pageInfo.getTotal(),list);
}
四 .拓展包--批量操作#
批量查询,批量删除
注意他的包啊!
Copy
import tk.mybatis.mapper.additional.idlist.IdListMapper;
public interface Mapper extends Mapper<Category> , IdListMapper<Category,Long> {}
Copy
/**
* 根据主键字符串进行查询,类中只有存在一个带有@Id注解的字段
* @param idList
* @return
*/
@SelectProvider(type = IdListProvider.class, method = "dynamicSQL")
List<T> selectByIdList(@Param("idList") List<PK> idList);
/**
* 根据主键字符串进行删除,类中只有存在一个带有@Id注解的字段
* @param idList
* @return
*/
@DeleteProvider(type = IdListProvider.class, method = "dynamicSQL")
int deleteByIdList(@Param("idList") List<PK> idList);
批量插入:
Copy
import tk.mybatis.mapper.additional.insert.InsertListMapper;
public interface BaseMapper<T> extends InsertListMapper<T> {}
@RegisterMapper
public interface InsertListMapper<T> {
@InsertProvider(
type = InsertListProvider.class,
method = "dynamicSQL"
)
int insertList(List<? extends T> var1);
}