[Spring]常用注解和技术汇总

注解

常用注解

@Valid    //使用hibernate validation的时候使用

@Validated //用spring  Validator 校验机制使用

@Entity     //实体类

@Table(name=" 表名")  

@Id  // 主键

@Pattern(regexp = "([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}", message = "邮箱错误")

@NotNull(message = "不能为空")

@NotBlank   //检查约束字符串是不是Null,最少一个非空白字符.

@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 

@EnableTransactionManagement  // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />

@MapperScan(basePackages = "com.test.dao", markerInterface = MyMapper.class)


// 加载properties中的配置
@ConfigurationProperties("test")
@Component
@PropertySource("classpath:test.properties")

缓存注解


@EnableCaching
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)


    @ConditionalOnMissingBean(name = "redisTemplate")


 

缓存注解的文章 https://blog.csdn.net/dreamhai/article/details/80642010

主键注解生成策略

主键生成策略
//生成32位UUID 不是标准的uuid而是去掉横杠的

  		@GenericGenerator(name = "idGenerator", strategy = "uuid") 
        @GeneratedValue(generator = "idGenerator")

//完整写法
	@GenericGenerator(name = "idGenerator", strategy = "org.hibernate.id.UUIDGenerator")
    @GeneratedValue(generator = "idGenerator")

常用的时间注解

该注解被insert 时会被触发

@CreatedDate   创建时间
@CreatedBy   创建人
@LastModifiedDate
@LastModifiedBy

使用方法

  1. 在启动类上添加 @EnableJpaAuditing
  2. 在entity类上添加 @EntityListeners(AuditingEntityListener.class)
  3. 在字段上添加 @CreatedDate

查询

// 继承接口
public interface **Repository extends JpaRepository<PjPrj, String>, JpaSpecificationExecutor {
}

关联关系

一对一

// 一个人只养一只狗

// Person
 	@OneToOne(targetEntity = Dog.class, cascade = CascadeType.PERSIST)
 	
    @JoinColumn(name = "dogid", referencedColumnName = "id")
    private Dog dog;

//Dog

在这里插入图片描述
person 表中就会将dog的id主键作为外键进行关联,完成一对一的关联关系

一对多

多对多

条件查询

  @Override
    public Page queryAll(PjPrj resources, Pageable pageable, String time) {

        Page all = pjPrjRepository.findAll(new Specification() {

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                //todo 条件查询

                if (!ObjectUtils.isEmpty(resources.getPjn())) {
                    list.add(criteriaBuilder.equal(root.get("pjn"), resources.getPjn()));
                }

                if (!ObjectUtils.isEmpty(time)) {
                    String[] split = time.split(",");

                    SimpleDateFormat sdfmat = new SimpleDateFormat("yyyy-MM-dd");
                    try {

                        list.add(criteriaBuilder.between(root.get("createtime"),
                                sdfmat.parse(split[0]),
                                sdfmat.parse(split[1])));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, pageable);

        return all;
    }

数据库配置

 #配置 Jpa
 spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
 


  #配置 Jpa
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    #        format_sql: true # 格式化 生成的sql
    open-in-view: true
  #    show-sql: true  # 显示sql语句
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章