Well, it's just a memo, so I thought I'd tweet it on twitter, but I dare to record it with qitta.
JPA hands-on, samples, explanation sites, etc. When writing code in various places, there are many omission sites where the explanation is missing because the Entity setting is made with copy and paste.
For example, let's say you have the following sample code
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="name")
private String name;
@Column(name="password")
private String password;
...
}
Question: Does this work alone?
Correct answer: Does not work
Reason: It doesn't work unless the key is defined on the DB. For example, in MySQL, it will not work unless you set AUTO_INCREMENT etc. in the key. ** ** So if you are using a table that generates UUID etc. from java and uses it as a key, please remove the @GeneratedValue annotation.
Don't contact us by looking at sites that don't explain this. .. ..
Conclusion: When using @GeneratedValue, set the DB as well. If not, remove it.
Recommended Posts