John Manak
John Manak

Reputation: 13558

JPA - using annotations in a model

My application runs on JPA/Hibernate, Spring and Wicket. I'm trying to convert our ORM from XML files to JPA annotations. 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:

<?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

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?

Upvotes: 3

Views: 2968

Answers (1)

Henning
Henning

Reputation: 16311

Mark the method as @Transient so Hibernate will ignore it:

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

By default, everything that looks like a getter is mapped.

Upvotes: 7

Related Questions