简体   繁体   English

JPA - 在模型中使用注释

[英]JPA - using annotations in a model

My application runs on JPA/Hibernate, Spring and Wicket. 我的应用程序运行在JPA / Hibernate,Spring和Wicket上。 I'm trying to convert our ORM from XML files to JPA annotations. 我正在尝试将我们的ORM从XML文件转换为JPA注释。 The annotated model looks like this: 带注释的模型如下所示:

@Entity
@Table(name = "APP_USER")
public class User extends BaseObject {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name="FIRST_NAME")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name="LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name="EMAIL")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return Returns firstName and lastName
     */
    public String getFullName() {
        return firstName + ' ' + lastName;
    }
}

Originally, though, it was without annotation and the mapping was described in User.hbm.xml: 最初,它没有注释,并且在User.hbm.xml中描述了映射:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="org.appfuse.model.User" table="app_user">
        <id name="id" column="id" unsaved-value="null">
            <generator class="increment"/>
        </id>
        <property name="firstName" column="first_name" not-null="true"/>
        <property name="lastName" column="last_name" not-null="true"/>
        <property name="email" column="email"/>
    </class>
</hibernate-mapping>

When I delete the mapping file and try to use just the annotations, the entityManagerFactory doesn't get created, with the exception 当我删除映射文件并尝试仅使用注释时,不会创建entityManagerFactory,但会出现异常

org.hibernate.PropertyNotFoundException: Could not find a setter for property fullName in class org.appfuse.model.User.

There's no mapping set for this property, because it's just a convenience method. 此属性没有映射集,因为它只是一种方便的方法。 What do I do wrong? 我做错了什么?

Mark the method as @Transient so Hibernate will ignore it: 将方法标记为@Transient以便Hibernate忽略它:

/**
 * @return Returns firstName and lastName
 */
@Transient
public String getFullName() {
    return firstName + ' ' + lastName;
}

By default, everything that looks like a getter is mapped. 默认情况下,映射了看起来像getter的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM