当前位置: 代码迷 >> Java Web开发 >> 急Hibernate中list映射~
  详细解决方案

急Hibernate中list映射~

热度:6384   发布时间:2013-02-25 21:22:49.0
急!!Hibernate中list映射~~在线等
我需要记录我插入的顺序这个功能,所以我用list映射。简单写了个Demo.
数据库
a表id,name两个字段
b表id,a_id,type,indexnum四个字段 其中indexnum由hibernate维护
POJO
public class Bbbb {

private Integer id;
private String type;
private Aaaa a;

public class Aaaa {

private Integer id;
private String name;
private List<Bbbb> bs = new ArrayList<Bbbb>();

hbm.xml
<hibernate-mapping>
  <class name="org.test.Aaaa" table="aaaa" schema="YANGMENG">
  <id name="id" type="java.lang.Integer">
  <column name="id" />
  <generator class="sequence">
  <param name="sequence">seq_au_id</param>
  </generator>
  </id>
  <property name="name" type="java.lang.String">
  <column name="name" not-null="true" />
  </property>
  <list name="bs" table="Bbbb" cascade="all" inverse="false"> 
  <key column="a_id"></key>
  <list-index column="index1"></list-index>
  <one-to-many class="org.test.Bbbb" />
  </list>
  </class>
</hibernate-mapping>
<hibernate-mapping>
  <class name="org.test.Bbbb" table="bbbb" schema="YANGMENG">
  <id name="id" type="java.lang.Integer">
  <column name="id" />
  <generator class="sequence">
  <param name="sequence">seq_ab_id</param>
  </generator>
  </id>
  <many-to-one name="a" class="org.test.Aaaa">
  <column name="a_id" not-null="true" />
  </many-to-one>
  <property name="type" type="java.lang.String">
  <column name="type" not-null="true" />
  </property>
  </class>
</hibernate-mapping>
TEST
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session = HibernateSessionFactory.getSession();
try {
Aaaa a = new Aaaa();
a.setName("111");
Bbbb b1 = new Bbbb();
b1.setA(a);
b1.setType("1111");
Bbbb b2 = new Bbbb();
b2.setA(a);
b2.setType("2222");
a.getBs().add(b1);
a.getBs().add(b2);
session.beginTransaction().begin();
session.save(a);
session.beginTransaction().commit();
Query query = session.createQuery("from Aaaa a");
List<Aaaa> list1 = query.list();
for (Aaaa aaaa : list1) {
System.out.println(aaaa.getId());
}

} catch (Exception e) {
e.printStackTrace();
}

}
现在运行报错,如下
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
  相关解决方案