Spring DATA JPA ORM

导包

<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]));

        }

    });

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值