日期:2014-05-17  浏览次数:20682 次

hibernate问题,急
作者和文章是一对多的关系,两个表映射关系如下:
<hibernate-mapping>
<class name="com.para.zyh.springmvc.model.Article" table="t_article">
<id name="arId">
<generator class="native"></generator>
</id>
<property name="title"></property>
<property name="content"></property>

<many-to-one name="author" class="com.para.zyh.springmvc.model.Author">
<column name="auId"></column>
</many-to-one>
</class>
</hibernate-mapping>




<hibernate-mapping>
<class name="com.para.zyh.springmvc.model.Author" table="t_author">
<id name="auId">
<generator class="native"></generator>
</id>
<property name="name"></property>

<set name="articles">
<key>
<column name="auId"></column>
</key>
<one-to-many class="com.para.zyh.springmvc.model.Article"/>
</set>
</class>
</hibernate-mapping>

hibernate配置如下:

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

  <session-factory>
  <property name="hbm2ddl.auto">create</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="connection.url">jdbc:mysql://localhost/test</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
   
  <mapping resource="com/para/zyh/springmvc/model/Article.hbm.xml"/>
  <mapping resource="com/para/zyh/springmvc/model/Author.hbm.xml"/>
 
   
  </session-factory>

</hibernate-configuration>




插数据代码:
public class Data {
public static void main(String[] args) {
Configuration cfg=new Configuration().configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

//第一行记录
Author au1=new Author();
au1.setName("慕容晓晓");

Set<Article> articles1=new HashSet<Article>();

Article ar1=new Article();
ar1.setAuthor(au1);
ar1.setTitle("下一个天亮");
ar1.setContent("等待下一个天亮的日子,你是风中的信子,我在风中等待着答案");

Article ar2=new Article();
ar2.setAuthor(au1);
ar2.setTitle("风一般的日子");
ar2.setContent("我的每一分钟等待着风一般的日子");

Article ar3=new Article();
ar3.setAuthor(au1);
ar3.setTitle("面朝大海");
ar3.setContent("面朝大海,春暖花开");

articles1.add(ar1);
articles1.add(ar2);
articles1.add(ar3);

au1.setArticles(articles1);



//第二行记录
Author au2=new Author();
au2.setName("雪花");

Set<Article> articles2=new HashSet<Article>();

Article ar4=new Article();
ar4.setAuthor(au2);
ar4.setTitle("天国的嫁衣");
a