我一直为这件事心烦意乱。我有一个类像这样拉动对象:
public UserDTO getUser(String login)
{
String jql = "select entity from User as entity where entity.abcUserId = :userID ";
Query query = _entityManager.createQuery(jql)
.setParameter("userID", login);
try
{
Object user = query.getSingleResult();
return ((User) user).extractObject();
}
catch(NoResultException e)
{
LOG.error(e.getMessage());
return null;
}
}
与它正在拉的类:
@Entity
@Table(name="ABC_User")
public class User implements Serializable,EntityObject<UserDTO>
{
private static final long serialVersionUID = 1L;
private Long id;
private String abcUserId;
private Company company;
private List<UserPreference> userPreferences;
@Id
@GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="Company_ID", nullable=false)
public Company getCompany()
{
return company;
}
public void setCompany(Company customer)
{
this.company = customer;
}
/**
* @return the userPreference
*/
@ElementCollection(fetch=FetchType.EAGER)
@JoinTable(name="ABC_USER_PREFERENCES")
@Cascade(value={org.hibernate.annotations.CascadeType.ALL})
public List<UserPreference> getUserPreferences()
{
if(userPreferences == null)
{
userPreferences = new ArrayList<UserPreference>();
}
return userPreferences;
}
/**
* @param userPreference the userPreference to set
*/
public void setUserPreferences(List<UserPreference> userPreferences)
{
this.userPreferences = userPreferences;
}
/**
* @return the abcUserId
*/
@Column(name="ABC_USER_ID", length=10, nullable=false)
public String getAbcUserId()
{
return abcUserId;
}
/**
* @param abcUserId the abcUserId to set
*/
public void setAbcUserId(String abcUserId)
{
this.abcUserId = abcUserId;
}
引用这个可嵌入对象:
@Embeddable
public class UserPreference implements Serializable
{
private static final long serialVersionUID = 1L;
private String prefKey;
private String prefValue;
public UserPreference() {}
public UserPreference(String key, String value)
{
this.prefKey = key;
this.prefValue = value;
}
@Column(nullable=false, length=255)
public String getPrefKey()
{
return prefKey;
}
public void setPrefKey(String key)
{
this.prefKey = key;
}
@Column(nullable=false, length=1048576)
public String getPrefValue()
{
return prefValue;
}
public void setPrefValue(String value)
{
this.prefValue = value;
}
}
所以,冗长的代码块被删除了一些东西,这是行不通的。每次我试图从数据库中拉一个用户,它抛出"SQLServerException:无效的列名'User_id'"。User_id从未在我的项目中引用(我已经检查过),它的总是 abc_user。我可以看到对象在Eclipse调试器中被拉到一起,它达到了添加UserPreferences列表的地步,然后解体了。如果我注释掉User类的UserPreferences部分,它就会成功拉出(并在使用它们的其他地方中断)。
我错过了什么?
参见以下代码部分
@Column(name="ABC_USER_ID", length=10, nullable=false)
public String getAbcUserId()
{
return abcUserId;
}
检查表是否有列名'ABC_USER_ID'。然后,尝试将此代码放在@JoinTable部分
尝试为User.id
定义@Column
。它有一个@Id
,但没有@Column
。可能是Hibernate假设该字段的列是_id,结果是'User_id',当它试图将返回的数据映射到对象时找不到它。