2012-05-06 21 views
2

在我的web应用程序中,我使用Hibernate和struts2。因为我需要以XML格式发回数据,所以我添加了SimpleXML框架。SimpleXML&hibernate播放不好吗?

我仍处于测试阶段。所以我给我的Store类添加了注释,这也是由Hibernate生成的POJO类。

我没有在我的XML中的数据。这里是我得到:

<store> 
    <storeID>0</storeID> 
</store> 

我反而认为此XML:

<store> 
    <storeID>2</storeID> 
    <storeName>JC Penny</storeName> 
</store> 

上存储类的代码看起来是这样的:

/** 
* Store generated by hbm2java 
*/ 
@Root(name="store") 
@Entity 
@Table(name="store" 
    ,catalog="shopperdb" 
) 
public class Store implements java.io.Serializable { 

    @Element(name="storeID") 
    private int id; 

    @Element(name="storeName" , required=false) 
    private String name; 
    @Id 

@Column(name="id", unique=true, nullable=false) 
public int getId() { 
    return this.id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

@Column(name="name", length=45) 
public String getName() { 
    return this.name; 
} 

public void setName(String name) { 
    this.name = name; 
} 
} 

另外这里的代码我使用休眠模式从数据库加载数据并将XML生成到我的日志文件中的操作:

 _sess = HibernateUtil.getSessionFactory().getCurrentSession(); 

    if (!_sess.isOpen()) _sess = HibernateUtil.getSessionFactory().openSession(); 

    _tx = _sess.beginTransaction(); 

    Store tempStore = (Store) _sess.load(Store.class, 2); 

    Serializer serializer = new Persister(); 

    serializer.write(tempStore, System.out); 

    _tx.commit(); 

顺便说一句,我从数据库中获得正确的数据,因为我有一些我从这篇文章中获得的打印语句。

非常感谢您的帮助,萨尔。

回答

1

我修好了!看起来在使用Hibernate时,LOAD方法返回的对象与查询LIST方法返回的对象不同(以某种方式)。去搞清楚!

所以我取代了以下行:

Store tempStore = (Store) _sess.load(Store.class, 2); 

有了这一个:

Store tempStore = (Store)_sess.createQuery("from Store s where s.id=:sid").setInteger("sid", 2).uniqueResult(); 

我不知道为什么。我也不确定任何性能后果