我的DAO中的函数(findByUsername)总是返回0行,无论我是否更改了实体类,即使从实体中删除注释也没有异常,只有0行。根据我发现的一些例子,这个代码在基于spring的应用程序中实现。
DAO :
@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 :
@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;
}
}
答案 0 :(得分:0)
解决方案是将导入声明更改为
import javax.persistence.Entity;
而不是休眠。 未导入用户实体类。