Jpa
概念
JPA是Java Persistence API的简称,是Sun公司提出的Java持久化规范。它是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
JPA是JCP组织发布的Java EE标准之一,因此任何声称符合JPA 标准的框架都遵循同样的架构,提供相同的访问API。(转自版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本文链接:https://blog.csdn.net/liuduke1/article/details/108239347)
有几种JPA写法(转载 https://blog.csdn.net/qq_39095899/article/details/107469151 @Repository标识用法,https://www.cnblogs.com/yanzhenyidai/p/12988598.html mvc写法)
配置
#数据库的方言,假如使用Oracle 就配置Oracle 的方言,MySql就配置MySql的方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
这部分可以改数据库方言 默认mysql
可以在控制台看
2021-02-08 10:06:19.782 INFO 13252 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
jpa:
show-sql: true #显示sql语句
hibernate:
ddl-auto: create #这部分可以设置create先(自动建表),update(后面改)
properties:
hibernate:
format_sql: true #格式化sql语句(美化语句)
花式条件查询
public interface BlogDao extends JpaRepository<Blog,Long>, JpaSpecificationExecutor<Blog> {
JpaSpecificationExecutorjie接口 分页查询 有很多查询方法
可以创建Specification对象然后查询对应属性值的是否包含
@Test
public void testSpecs() {
userDao.save(new User(null, "summerday", "123456", "hangzhou"));
userDao.save(new User(null, "summy", "1256", "Beijing"));
userDao.save(new User(null, "summerdy", "3456", "HongKong"));
userDao.save(new User(null, "summerda", "1256", "Shanghai"));
//Specification对象调用方法 设置属性值 值
Specification<User> specification = UserSpecs.contains("username", "summer");
List<User> all = userDao.findAll(specification);
System.out.println(all);
}
直接创建对象加入查询条件
@Test
public void findByExample() {
Specification<Blog> specification = new Specification<Blog>() {
@Override
public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new LinkedList<>();
predicates.add(cb.equal(root.get("status"), 1)); // 查询status状态为1
predicates.add(cb.like(root.get("author"), "%summer%")); // author名称中存在summer
predicates.add(cb.between(root.get("publishTime"), // 发布时间7天前至今
Date.from(Instant.now().minus(Duration.ofDays(7))), new Date()));
return cb.and(predicates.toArray(new Predicate[0]));
}
};
// 按照条件查询,并按照publish_time升序
List<Blog> blogs
= blogDao.findAll(specification, Sort.by(Sort.Direction.ASC, "publishTime"));
blogs.forEach(System.out::println);
}
多表查询
映射的注解
@OneToOne
@ManyToOne
@ManyToMany
JPQL查询
@Query(value = “update Customer set custName=? where custId=?”)
public Customer findByNameAndId(Long id,String name);
转自https://blog.csdn.net/qq_36639232/article/details/106116274
代码参考
https://gitee.com/tqbx/springboot-samples-learn/tree/master/spring-boot-jpa