Jpa元模型属性,不能定义父类继承的属性吗?
怎么解决这个问题?
父类 BaseEntity
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.LocalDateTime;
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = -8506961188930650652L;
@Column(name = "version", columnDefinition = "INT(11) UNSIGNED COMMENT '版本号'")
private Integer version;
@Column(name = "create_date", columnDefinition = "TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'")
private LocalDateTime createDate;
}
子类 User
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
@org.hibernate.annotations.Table(appliesTo = "user", comment = "用户表")
public class User extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 8175166175439387541L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(columnDefinition = "varchar(20) COMMENT '昵称'")
private String name;
}
元模型
import java.time.LocalDateTime;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(User.class)
public abstract class User_ {
public static volatile SingularAttribute<User, Integer> id;
public static volatile SingularAttribute<User, String> name;
public static volatile SingularAttribute<User, Integer> version; // 父类继承的属性
public static volatile SingularAttribute<User, LocalDateTime> createDate; // 父类继承的属性
}
测试
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("mysql");
CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
try {
CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
Predicate predicate = criteriaBuilder.greaterThan(root.get(User_.createDate), LocalDateTime.now()); // java.lang.NullPointerException
criteriaQuery.where(predicate);
entityTransaction.commit();
}catch (Exception e) {
entityTransaction.rollback();
throw e;
}finally {
entityManager.close();
entityManagerFactory.close();
}
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.query.criteria.internal.path.AbstractPathImpl.get(AbstractPathImpl.java:123)
at io.springboot.jpa.JpaApplication.main(JpaApplication.java:46)