Hibernate保存实体不起作用

时间:2014-10-13 23:26:46

标签: xml hibernate

我有以下代码,

try {
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

      //Get Session
      Session session = sessionFactory.getCurrentSession();

      //start transaction
      session.beginTransaction();

      Department dept = DepartmentDAO.findDepartmentById(sessionFactory, 115); // Administration
      Country cntr = CountryDAO.findCountryById(sessionFactory, new Short((short)102)); // UK
      City ct = CityDAO.findCityById(sessionFactory, new Short((short)312)); // London
      Address address = AddressDAO.findAddressById(sessionFactory, new Short((short)517)); // Street of London

      System.out.println("Department: " + dept.getDepartmentName());
      System.out.println("Country: " + cntr.getCountry());
      System.out.println("City: " + ct.getCity());
      System.out.println("Address: " + address.getAddress());

      Users user = new Users();
      user.setUsername("alan");
      user.setPassword(LoginConverter.hash256("alan"));
      user.setRoles(Roles.ADMINISTRATOR);

      Employees emp = new Employees();
      emp.setName("Alan");
      emp.setJobRole("CEO");
      emp.setInsertTime(new Date());
      emp.setDepartment(dept);
      emp.setAddress(address);

      emp.setUser(user);
      user.setEmployee(emp);

      session.save(emp);
      session.save(user);

      //Commit transaction
      session.getTransaction().commit();

      System.out.println("************* OK *************");
      System.out.println("************* OK *************");
      System.out.println("************* OK *************");
      System.out.println("************* OK *************");

} catch(HibernateException | NoSuchAlgorithmException | UnsupportedEncodingException t) {

      System.out.println("************* KO *************");
      System.out.println("************* KO *************");
      System.out.println("************* KO *************");
      System.out.println("************* KO *************");

} finally {
      //terminate session factory, otherwise program won't end
      HibernateUtil.closeSessionFactory();
}

它不起作用。

这是实体关系的hbm映射文件,

country.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Country" table="country">
    <id name="countryId" type="java.lang.Short" column="COUNTRY_ID" >
        <generator class="native" />
    </id> 
    <property name="country" type="java.lang.String">
      <column name="COUNTRY"/>
    </property>
    <property name="lastUpdate" type="timestamp">
      <column name="LAST_UPDATE"/>
    </property>
    <bag name="cityList" table="city"
            inverse="true" lazy="true" fetch="select">
        <key>
            <column name="city_id" not-null="true" />
        </key>
        <one-to-many class="com.journaldev.hibernate.model.City" />
    </bag>
</class>
</hibernate-mapping>

city.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.City" table="city">
    <id name="cityId" type="java.lang.Short" column="CITY_ID" >
        <generator class="native" />
    </id>
    <property name="city" type="java.lang.String">
      <column name="CITY"/>
    </property>
    <property name="lastUpdate" type="timestamp">
      <column name="LAST_UPDATE"/>
    </property>
    <bag name="addressList" table="address"
            inverse="true" lazy="true" fetch="select">
        <key>
            <column name="ADDRESS_ID" not-null="true" />
        </key>
        <one-to-many class="com.journaldev.hibernate.model.Address" />
    </bag>
    <many-to-one name="country" class="com.journaldev.hibernate.model.Country" fetch="select">
        <column name="COUNTRY_ID" not-null="true" />
    </many-to-one>
</class>
</hibernate-mapping>

address.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Address" table="address">
    <id name="addressId" type="java.lang.Short" column="ADDRESS_ID" >
        <generator class="native" />
    </id>
    <property name="address" type="java.lang.String">
      <column name="ADDRESS"/>
    </property>
    <property name="address2" type="java.lang.String">
      <column name="ADDRESS2"/>
    </property>
    <property name="district" type="java.lang.String">
      <column name="DISTRICT"/>
    </property>
    <property name="postalCode" type="java.lang.String">
      <column name="POSTAL_CODE"/>
    </property>
    <property name="phone" type="java.lang.String">
      <column name="PHONE"/>
    </property>
    <property name="lastUpdate" type="timestamp">
      <column name="LAST_UPDATE"/>
    </property>
    <many-to-one name="city" class="com.journaldev.hibernate.model.City" fetch="select">
        <column name="city_id" not-null="true" />
    </many-to-one>
    <bag name="employeesList" table="EMPLOYEES"
            inverse="true" lazy="true" fetch="select">
        <key>
            <column name="id" not-null="true" />
        </key>
        <one-to-many class="com.journaldev.hibernate.model.Employees" />
    </bag>
</class>
</hibernate-mapping>

users.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Users" table="USERS">
  <id name="id" type="java.lang.Integer">
    <column name="ID"/>
    <generator class="foreign">
      <param name="property">employee</param>
    </generator>
  </id>
  <one-to-one cascade="save-update, delete" class="com.journaldev.hibernate.model.Employees" name="employee"/>
  <property name="username" type="java.lang.String">
    <column name="USERNAME"/>
  </property>
  <property name="password" type="java.lang.String">
    <column name="PASSWORD"/>
  </property>
  <property name="roles"
          type="com.journaldev.hibernate.model.RolesUserType"
          update="true"
          insert="true"
          access="property"
          not-null="true">
    <column name="roles_user_type" />
  </property>
</class>
</hibernate-mapping>

employees.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Employees" table="EMPLOYEES">
    <id name="id" type="java.lang.Integer">
        <column name="ID"/>
        <generator class="foreign">
            <param name="property">user</param>
        </generator>
    </id>
    <one-to-one class="com.journaldev.hibernate.model.Users" constrained="true" name="user"/>
    <property name="name" type="java.lang.String">
        <column name="NAME"/>
    </property>
    <property name="jobRole" type="java.lang.String">
        <column name="ROLE"/>
    </property>
    <property name="insertTime" type="timestamp">
        <column name="INSERT_TIME"/>
    </property>
    <many-to-one name="address" class="com.journaldev.hibernate.model.Address" fetch="select">
        <column name="ADDRESS_ID" not-null="true" />
    </many-to-one>
    <many-to-one name="department" class="com.journaldev.hibernate.model.Department" fetch="select">
        <column name="DEPARTMENT_ID" not-null="true" />
    </many-to-one>
</class>
</hibernate-mapping>

department.hbm.xml

<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Department" table="department">
    <id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID" >
        <generator class="native" />
    </id>
    <property name="departmentName" type="java.lang.String">
        <column name="DEPT_NAME"/>
    </property>
    <bag name="employees" table="employees"
            inverse="true" lazy="true" fetch="select">
        <key>
            <column name="ID" not-null="true" />
        </key>
        <one-to-many class="com.journaldev.hibernate.model.Employees" />
    </bag>
</class>
</hibernate-mapping>

这是输出和它给我的例外,

  

Hibernate:选择country0_.COUNTRY_ID作为COUNTRY_1_4_0_,country0_.COUNTRY作为COUNTRY2_4_0_,&gt;&gt; country0_.LAST_UPDATE作为LAST_UPD3_4_0_来自国家country0_,其中country0_.COUNTRY_ID =?

     

Hibernate:选择city0_.CITY_ID为CITY_ID1_3_0_,city0_.CITY为CITY2_3_0_,city0_.LAST_UPDATE为&gt;&gt; LAST_UPD3_3_0_,city0_.COUNTRY_ID为COUNTRY_4_3_0_来自city city0_,其中city0_.CITY_ID =?

     

休眠:选择地址0_.ADDRESS_ID作为ADDRESS_1_2_0_,地址0_ADDRESS作为ADDRESS2_2_0_,&gt;&gt;地址0_.ADDRESS2作为ADDRESS3_2_0_,地址0_.DISTRICT作为DISTRICT4_2_0_,地址0_.POSTAL_CODE作为&gt;&gt; POSTAL_C5_2_0_,地址0_.PHONE作为PHONE6_2_0_, address0_.LAST_UPDATE为LAST_UPD7_2_0_,&gt;&gt;&gt;地址0_.city_id为city_id8_2_0_,来自地址address0_,其中address0_.ADDRESS_ID =?

     
    

部门:行政

         

国家:英国

         

城市:伦敦

         

地址:乌鲁阿潘街548号

  
oct 14, 2014 12:29:14 AM
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
  at com.sun.proxy.$Proxy0.save(Unknown Source)
  at com.journaldev.hibernate.main.Main.main(Main.java:70)
Caused by: java.lang.reflect.InvocationTargetException
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:483)
  at    org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
... 2 more
Caused by: java.lang.StackOverflowError
  at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1094)
  at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1452)
  at  org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
  at  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
  at  org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
  at  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
  at  org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
  at  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
  at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
  at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
  at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:123)
  at  org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
  at  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
  at  org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
  at  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)

----------

......还有更多

但事实上,当我执行项目文件时,该项目是maven,它在构建时失败。

那么请问,我该怎样做才能实现这种行为?

由于

1 个答案:

答案 0 :(得分:0)

这里你有一个正确的users.hbm.xml和employees.hbm.xml文件是它们之间的关系,一对一,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Users" table="users">
    <id name="id" type="java.lang.Integer" column="id">
        <generator class="native" />
    </id>
    <one-to-one cascade="save-update, delete" class="com.journaldev.hibernate.model.Employees" name="employee"/>
    <property name="username" type="java.lang.String">
        <column name="username"/>
    </property>
    <property name="password" type="java.lang.String">
        <column name="password"/>
    </property>
    <property name="roles"
          type="com.journaldev.hibernate.model.RolesUserType"
          update="true"
          insert="true"
          access="property"
          not-null="true">
        <column name="roles_user_type" />
    </property>
</class>
</hibernate-mapping>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.journaldev.hibernate.model.Employees" table="employees">
    <id name="id" type="java.lang.Integer">
        <column name="id"/>
        <generator class="foreign">
            <param name="property">user</param>
        </generator>
    </id>
    <one-to-one class="com.journaldev.hibernate.model.Users" constrained="true" name="user"/>
    <property name="name" type="java.lang.String">
        <column name="name"/>
    </property>
    <property name="jobRole" type="java.lang.String">
        <column name="role"/>
    </property>
    <property name="insertTime" type="timestamp">
        <column name="insert_time"/>
    </property>
    <many-to-one name="address" class="com.journaldev.hibernate.model.Address" fetch="select">
        <column name="address_id" not-null="true" />
    </many-to-one>
    <many-to-one name="department" class="com.journaldev.hibernate.model.Department" fetch="select">
        <column name="department_id" not-null="true" />
    </many-to-one>
</class>
</hibernate-mapping>

由于