导包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://111.111.111.111:3306/aa
username: root
password: root
jpa:
properties:
hibernate:
hbm2ddl:
auto: update #没有表会自动创建
dialect: org.hibernate.dialect.MySQL5InnoDBDialect #方言mysql和
format_sql: true #打印sql语句格式
show-sql: true #展示sql语句
启动类
@SpringBootApplication //启动注解
public class MybatisPlusSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusSpringbootApplication.class, args);
}
}
实体类
@Entity //表示这是一个实体
@Table(name = "tb_label") //name = 表名
public class Label {
@Id //此属性为ID
@GeneratedValue(strategy = GenerationType.IDENTITY) //ID生成机制
@Column(name = "id") // 与表字段一致 则可以不加
private Long id;
private String labelname;
private String state;
private Long count;
private String recommend;
private Long fans;
}
DAO接口
public interface LabelDao extends JpaRepository<Label, Long>, JpaSpecificationExecutor<Label> {
}
JpaRepository<Label, Long> -- 表示简单的CRUD操作。
Label 表示要操作的实体类
Long 表示实体类的主键类型
JpaSpecificationExecutor<Label> -- 只做查询,用于复杂的查询。
Label 表示要操作的实体类
复制查询
@Test
public void query(){
Label label = new Label();
List<Label> all = labelDao.findAll(new Specification<Label>() {
@Override
public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
ArrayList<Predicate> list = new ArrayList<Predicate>();
if(label!=null){
if(!StringUtils.isEmpty(label.getLabelname())){
Predicate like = cb.like(root.get("labelname").as(String.class), label.getLabelname());
list.add(like);
}
if(label.getCount()!=null){
Predicate count = cb.equal(root.get("count"), label.getCount());
list.add(count);
}
}
return cb.and(list.toArray(new Predicate[0]));
}
});
}