java - 使用 JPA hibernate ,忽略 @Formula

标签 java hibernate jakarta-ee jpa persistence

我有一个 Formula 定义为:

@Entity
@Table(name = "MyEntity")
@org.hibernate.annotations.Table(appliesTo = "MyEntity")
public class MyEntity
{
    @Enumerated(value = javax.persistence.EnumType.STRING)
    @Transient
    @Formula(value = "select e.state from OTHER_ENTITY e")
    private State state;

    public State getState()
    {
        return this.state;
    }
//setter and another properties
}

但它忽略了它。

这是我的持久化单元:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myPersistence" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <mapping-file>META-INF/orm.xml</mapping-file>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.connection.url" value="jdbc:mysql://url:3306/db" />
        <property name="hibernate.connection.username" value="root" />
        <property name="hibernate.connection.password" value="root" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="validate" />
    </properties>
</persistence-unit>

生成的sql没有Formula

如果我删除 @TransientJPA 会尝试加载 state 列,然后失败。

我想根据另一个实体的状态计算状态。这就是我认为 Formula 有效的原因。

谢谢!

乌多。

最佳答案

您正在尝试两次映射状态:一次是通过向字段添加注释,一次是通过向 getter 添加注释。把所有的注解放在同一个地方(和@Id注解在同一个地方)。

但这确实令人困惑。你的状态是 transient 的(意味着它根本没有映射,不应该从数据库中读取),但它也是枚举的(为什么 Hibernate 使用这个注释,因为它应该是 transient 的)和一个公式。

最后,公式是添加到用于加载实体的每个 SQL 中的一段 SQL。因此它不应包含 select 子句或 from 子句,而应仅包含使用表本身的某些列的公式。例如,假设您有一个包含 salary 列和 bonus 列的表,您可以为 totalIncome 字段创建一个公式,该公式为'奖金+工资'。但 id 并没有比这更进一步。

关于java - 使用 JPA hibernate ,忽略 @Formula,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824805/

相关文章:

java - 如何向此 TextView 添加自定义字体?

java - java合并xml文件

java.lang.ClassNotFoundException : org. springframework.orm.hibernate.support.OpenSessionInViewFilter 问题

mysql - HHH000203 : processEqualityExpression() : No expression to process

java - Java EE 项目中的错误

Java:使用 split 方法添加时,字符串数组列表中出现额外的空格

java - 动态 hibernate 查询

java - @AdditionalCriteria 作用于 EclipseLink 中的变量而不是类

java - 如何在JSF中 "hide"文本的最后一部分

java - 如何启用 MessageDrivenContext 注入(inject)?