Saturday, April 17, 2010

Identity Crisis: JPA @Id

Who am I?

Allow me to show you a simple JPA mapping,

@MappedSuperclass
public class Domain implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQ")
private Integer id;

public Integer getId() {
return id;
}

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



Do you see the thorny issue here?

Look again.

Yes, you're right - the setter method!

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQ")

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



In my view, the setter method should not be there at all as id property is marked as "sequence". How often do you invoke setId(Integer) method? I believe rarely or almost never.

A question emerges from the back of your mind - "But I need that for my unit test?!".

If you populate this property yourself, then there's something wrong with your unit test and I strongly suggest that you rethink the way you write your test code.

I admit I've done this before many times. You are not alone my friend.

"Who is it that can tell me who I am?"