我是 JPA 的新手,我对来自存储库的这个示例代码有疑问:
@Override
public boolean add(User user) {
EntityManagerFactory emf = HibernateRepositoryFactory
.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
User tempUser = null;
try {
if (user.getId() != null) {
tempUser = em.find(User.class, user.getId());
}
if (tempUser == null) {
em.persist(user);
} else {
// if so, get the differences and persist them
tempUser.setPassword(user.getPassword());
tempUser.setUserName(user.getUserName());
tempUser = em.merge(user);
}
} catch (Exception e) {
logging.error("log error+ " :" + e);
}
tx.commit();
em.close();
emf.close();
return true;
}
与实体:
@Entity
@Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false, unique = true)
private Long id;
@Version
@Column(name = "OPTLOCK")
private int version;
@Column(name = "USERNAME", nullable = false)
private String userName;
@Column(name = "PASSWORD", nullable = false)
private String password;
public User() {
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return id;
}
public int getVersion() {
return version;
}
}
我完全不明白。
在该行中: if (user.getId() != null) user.getId 将始终为 null,因为我相信 id 将在对象被持久化的那一刻生成?像这样 tempUser 永远不会从数据库中填充,并且对象将始终被持久化而不是合并.... 还是我看错了?
查看您是否需要像这样坚持或合并的最佳方法是什么。
编辑
如果我会使用这样的 main 怎么办:
User user1 = new User();
user1 .setPassword("password_user1");
user1 .setUserName("userName_user1");
... .add(user1);
如果我运行一次,则添加用户。如果我再次运行此用户,则再次使用 id+1