Make hibernate ignore class variables that are not mapped

JavaHibernateJpa

Java Problem Overview


I thought hibernate takes into consideration only class variables that are annotated with @Column. But strangely today when I added a variable (that is not mapped to any column, just a variable i need in the class), it is trying to include that variable in the select statement as a column name and throws the error -

>Unknown column 'team1_.agencyName' in 'field list'

My class -

@Entity
@Table(name="team")
public class Team extends BaseObject implements Serializable {

@Id  @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(length=50)
private String name;

@Column(length=10)
private String code;

@Column(name = "agency_id")
private Long agencyId;

private String agencyName; //note: not annotated.

}

FYI...I use the above class in another class with many to many mapping

@ManyToMany(fetch = FetchType.EAGER) 
@JoinTable(
        name="user_team",
        joinColumns = { @JoinColumn( name="user_id") },
        inverseJoinColumns = @JoinColumn( name="team_id")
)    
public Set<Team> getTeams() {
    return teams;
}

Why is this happening?!

Java Solutions


Solution 1 - Java

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

Solution 2 - Java

For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient. Make sure that you import javax.persistence.transient and not some other package.

Solution 3 - Java

Placing @Transient on getter with private field worked for me.

private String name;

	@Transient
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionheseView Question on Stackoverflow
Solution 1 - JavaskaffmanView Answer on Stackoverflow
Solution 2 - JavaCodeMedView Answer on Stackoverflow
Solution 3 - JavaSaumyarajView Answer on Stackoverflow