EntityManager.merge() 可以插入新对象并更新现有对象.
为什么要使用persist()(只能创建新对象)?
我是Java Persistence API和Hibernate的新手.
Java Persistence API FetchType.LAZY和之间的区别是什么FetchType.EAGER?
的JPA(Java持久性API)规范有2名不同的方式来指定实体组合键:@IdClass和@EmbeddedId.
我在我的映射实体上使用了两个注释,但对于那些不熟悉的人来说,结果却是一团糟JPA.
我想只采用一种方法来指定复合键.哪一个真的最好?为什么?
我正在使用该javax.persistence包来映射我的Java类.
我有这样的实体:
public class UserEntity extends IdEntity {
}
Run Code Online (Sandbox Code Playgroud)
它扩展了一个名为的映射超类IdEntity:
@MappedSuperclass
public class IdEntity extends VersionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// Getters and setters below...
}
Run Code Online (Sandbox Code Playgroud)
该IdEntity超类扩展了另一个名为映射超类VersionEntity,使所有实体继承版本特性:
@MappedSuperclass
public abstract class VersionEntity {
@Version
private Integer version;
// Getters and setters below...
}
Run Code Online (Sandbox Code Playgroud)
为什么?
因为现在我可以在所有实体的IdEntity类上进行泛型查询,它看起来像这样:(示例)
CriteriaBuilder builder = JPA.em().getCriteriaBuilder();
CriteriaQuery<IdEntity> criteria = builder.createQuery(IdEntity.class);
Run Code Online (Sandbox Code Playgroud)
现在来问题了.
我的一些实体将有created_at和时间戳一样的deleted_at.但并非所有实体.
我可以在我的实体类中提供这些属性,如下所示:
public class UserEntity …Run Code Online (Sandbox Code Playgroud) 我有一个包含作者列表的书类:
@Entity
@Table(name = "book")
public class Book extends Content {
@ManyToMany(fetch = FetchType.LAZY)
private List<Author> authors;
...}
Run Code Online (Sandbox Code Playgroud)
现在,这是我的BookSpecifications班级:
public static Specification<Book> authorIdIs(Long authorId) {
return new Specification<Book>() {
@Override
public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
return cb.isTrue(root.get("authors").get("id").in(authorId));
}
};
}
Run Code Online (Sandbox Code Playgroud)
如何检查authorId列表中的给定内容?
错误:
java.lang.IllegalStateException: Illegal attempt to dereference path source [null.authors] of basic type
at org.hibernate.jpa.criteria.path.AbstractPathImpl.illegalDereference(AbstractPathImpl.java:98) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:191) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at com.tarameshgroup.derakht.service.specs.BookSpecifications$3.toPredicate(BookSpecifications.java:40) ~[classes/:na]
at org.springframework.data.jpa.domain.Specifications$ComposedSpecification.toPredicate(Specifications.java:189) ~[spring-data-jpa-1.9.2.RELEASE.jar:na]
Run Code Online (Sandbox Code Playgroud) jpa ×5
java ×4
hibernate ×2
annotations ×1
criteria-api ×1
inheritance ×1
merge ×1
orm ×1
persist ×1
spring ×1