无论我是否更改实体类,DAO中的函数(findByUsername)始终返回0行,即使从实体中删除注释后也没有例外,只有0行。根据我发现的一些示例,该代码在基于spring的应用程序中实现。
道:
@Repository("userDao")
public class UserDao extends CustomHibernateDaoSupport {
public void save(User user) {
getHibernateTemplate().save(user);
}
public void delete(User user) {
getHibernateTemplate().delete(user);
}
public User findByUsername(String username) throws DataNotFoundException {
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
System.out.println(username);
crit.add(Restrictions.eq("username", username));
crit.setMaxResults(1);
List<User> users = crit.list();
System.out.println(users);
if (users.size() < 1) {
throw new DataNotFoundException();
}
return users.get(0);
}
}
实体:
@Entity
@Table(name = "users")
public class User {
private Integer id;
private String username;
private String password;
private boolean active;
private String activationCode;
private Date createdAt;
private String email;
private Set<Wall> walls = new HashSet<Wall>();
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "username", unique = true, nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "active")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Column(name = "activation_code")
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
@Column(name = "created_at", columnDefinition = "DATETIME")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "users_has_walls", joinColumns = {
@JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "wall_id",
nullable = false, updatable = false) })
public Set<Wall> getWalls() {
return walls;
}
public void setWalls(Set<Wall> walls) {
this.walls = walls;
}
}
最佳答案
解决方案是将进口申报单更改为
import javax.persistence.Entity;
而不是冬眠。
用户实体类未导入。