LoginSignup
6
8

More than 5 years have passed since last update.

HibernateでEntityに関係ないアクセサを定義したい

Posted at

HibernateのEntityにフィールドで宣言していないプロパティのgetter、setterを定義すると、
起動時にプロパティが見つからないと言われて、エラーが発生する。

private String skills;

// setterは省略
@Column(name="skills")
public String getSkills() {
    return skills;
}

public int getRowCount() { // これに該当するプロパティが宣言されていないので、エラー。
    return rowCount;
}

解決策1:@Transientを使用する。

使用したいアクセサに@Transientをつける。

private String skills;

// setterは省略
@Column(name="skills")
public String getSkills() {
    return skills;
}

@Transient
public int getRowCount() { // これに該当するプロパティが宣言されていない。
    return rowCount;
}

解決策2:getter、setterのメソッド名をやめる。

要するにis〜とか、get〜、set〜とかのメソッド名をやめれば一応動く。

private String skills;

// setterは省略
@Column(name="skills")
public String getSkills() {
    return skills;
}

public int takeRowCount() { // get → takeに変える。(意味的には変わらない)
    return rowCount;
}

まぁ、でも自分だったら@Transientを使うかな。

参考URL
http://stackoverflow.com/questions/6107387/is-it-possible-to-ignore-some-field-when-mapping-in-annotation-entity-class
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8