註解
常用註解
@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
使用方法
- 在啓動類上添加 @EnableJpaAuditing
- 在entity類上添加 @EntityListeners(AuditingEntityListener.class)
- 在字段上添加 @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語句