2015-05-04 51 views
1

我有兩個類,UserPackage。 A User可以有多個PackagePackage可以有多個User與之關聯。所以我有一個多對多的關聯。在我的數據庫中,我有三個表:一個用於用戶,一個用於軟件包和Package-User表。使用Hibernate保存在@ManyToMany關聯

我已經測試了映射。我可以單獨保存UserPackage,但是當我嘗試保存包含與其關聯的用戶列表的Package時,我無法這樣做,我也不知道爲什麼。

這是我如何映射與Hibernate類:

Package: 

    @ManyToMany(fetch=FetchType.LAZY) 
     @JoinTable(name="license_usage", 
     joinColumns={@JoinColumn(name="id_package")}, 
     inverseJoinColumns={@JoinColumn(name="id_user")}) 
     private Collection<PbrUser> pbrUsers; 

Users: 

    @ManyToMany(fetch=FetchType.LAZY) 
     @JoinTable(name="license_usage", 
     [email protected](name="id_user"), 
     [email protected](name="id_package")) 
     private Collection<Package> packages; 

處理功能,其中我集相關聯的包,並傳遞給所述控制器,以保存到數據庫中的用戶的列表:

Package pack = new Package(); 
      //System.out.println("Zerei? "+ petrelLicensesInUse); 
      while (i < reportContent.size()){ 
       phrase = reportContent.get(i); 
       if(phrase.contains(Constants.licenseUsageIdentifier)){ 
        licenseUsage = true; 
        licenseUser = false; 
        licenseIssued = phrase.substring((phrase.indexOf(Constants.totalLicenseAvailableId) + 10),phrase.indexOf(Constants.endLicensesIssued)); 
        licenseUsed = phrase.substring((phrase.indexOf(Constants.totalLicenseUsedId) + 12),phrase.indexOf(Constants.endLicensesUsed)); 
        licenseIssuedNum = Integer.parseInt(licenseIssued); 
        licenseUsedNum = Integer.parseInt(licenseUsed); 
        licenseUsageList.add(phrase.replaceAll("; Total of ", ", Used: ").replaceAll("Users of ", "") 
          .replaceAll(" licenses issued", "").replaceAll(" licenses in use", "").replaceAll("Total of", "Total:") 
          .replaceAll(" license in use", "").replaceAll(" license issued", "").replace(" ", " ")); 
        if(licenseUsedNum != 0){ 
         pack.setUsers(new ArrayList<PbrUser>()); 
        } 
       } 

       if(phrase.contains(Constants.licenseUserIdentifier)){ 
        licenseUsage = false; 
        licenseUser = true; 
        currPckg = phrase.substring((phrase.indexOf(Constants.licenseUserIdentifier) + 1),phrase.indexOf(Constants.licenseUserIdentifier + " ")); 
        version = phrase.substring((phrase.indexOf(Constants.version) + 3),phrase.indexOf(Constants.endVersion)); 
        vendorDaemon = phrase.substring((phrase.lastIndexOf(' ') + 1)); 
        pack.setNamePackage(currPckg); 
        pack.setVersion(version); 
        pack.setVendorDaemon(vendorDaemon); 
        pack.setNumberOfPackageLicenses(licenseIssuedNum); 

        //PackageController.create(pack); 
       } 


       if(licenseUser && phrase.contains(Constants.userStartDateId)){ 
        //System.out.println(phrase.indexOf(Constants.userStartDateId)); 
        currDate = transformDate(phrase.substring((phrase.indexOf(Constants.userStartDateId)+Constants.userStartDateId.length()),phrase.length())); 
        //System.out.println(phrase.substring(Constants.spaceUntilUser +1,phrase.length()).indexOf(" ")); 
        currName = phrase.substring(Constants.spaceUntilUser, (Constants.spaceUntilUser + phrase.substring(Constants.spaceUntilUser +1,phrase.length()).indexOf(" ")+1)); 
        PbrUser pbrUser = new PbrUser(currName); 
        //PbrUserController.create(pbrUser); 
        reportMetadataList.add(new ReportMetadata(currName, currPckg, currDate)); 
        if(licenseUsedNum != 0){ 
         //PbrUser pbrUser = new PbrUser(currName); 
         pack.getUsers().add(pbrUser); 
        } 
        contSave++; 
       } 

       if(licenseUser && contSave == licenseUsedNum){ 
        PackageController.create(pack); 
        contSave=0; 
       } 

       i++; 
      } 

SaveOrUpdate功能:

static protected void insert(Object object){ 
     Transaction tx = null; 
     Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession(); 
     try { 
      tx = session.beginTransaction(); 
      session.saveOrUpdate(object); 
      tx.commit(); 
     } catch (RuntimeException e) { 
      if (tx != null && tx.isActive()) { 
      try { 
    // Second try catch as the rollback could fail as well 
       tx.rollback(); 
      } catch (HibernateException e1) { 
       logger.debug("Error rolling back transaction"); 
      } 
    // throw again the first exception 
      throw e; 
      } 
     } 
    } 

日誌輸出:

11:25:05,013 DEBUG logging:194 - Logging Provider: org.jboss.logging.Log4jLoggerProvider 
    11:25:05,560 INFO Version:66 - HCANN000001: Hibernate Commons Annotations {4.0.5.Final} 
    11:25:05,591 INFO Version:54 - HHH000412: Hibernate Core {4.3.8.Final} 
    11:25:05,607 INFO Environment:224 - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5} 
    11:25:05,623 INFO Environment:346 - HHH000021: Bytecode provider name : javassist 
    11:25:05,747 INFO Configuration:2075 - HHH000043: Configuring from resource: /hibernate.cfg.xml 
    11:25:05,747 INFO Configuration:2094 - HHH000040: Configuration resource: /hibernate.cfg.xml 
    11:25:06,091 INFO Configuration:2216 - HHH000041: Configured SessionFactory: null 
    11:25:09,690 INFO Configuration:2075 - HHH000043: Configuring from resource: /hibernate.cfg.xml 
    11:25:09,690 INFO Configuration:2094 - HHH000040: Configuration resource: /hibernate.cfg.xml 
    11:25:09,691 INFO Configuration:2216 - HHH000041: Configured SessionFactory: null 
    11:25:09,753 WARN DriverManagerConnectionProviderImpl:93 - HHH000402: Using Hibernate built-in connection pool (not for production use!) 
    11:25:09,831 INFO DriverManagerConnectionProviderImpl:166 - HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/licensecontrol] 
    11:25:09,831 INFO DriverManagerConnectionProviderImpl:175 - HHH000046: Connection properties: {user=postgres, password=****} 
    11:25:09,831 INFO DriverManagerConnectionProviderImpl:180 - HHH000006: Autocommit mode: false 
    11:25:09,831 INFO DriverManagerConnectionProviderImpl:102 - HHH000115: Hibernate connection pool size: 1 (min=1) 
    11:25:10,988 INFO Dialect:145 - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect 
    11:25:11,052 INFO LobCreatorBuilder:123 - HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException 
    11:25:11,957 WARN RootClass:288 - HHH000038: Composite-id class does not override equals(): schlumberger.sis.licenseControl.model.LicenseUsagePK 
    11:25:11,957 WARN RootClass:289 - HHH000039: Composite-id class does not override hashCode(): schlumberger.sis.licenseControl.model.LicenseUsagePK 
    11:25:12,004 INFO TransactionFactoryInitiator:62 - HHH000399: Using default transaction strategy (direct JDBC transactions) 
    11:25:12,005 INFO ASTQueryTranslatorFactory:47 - HHH000397: Using ASTQueryTranslatorFactory 
    11:25:14,238 INFO SchemaUpdate:207 - HHH000228: Running hbm2ddl schema update 
    11:25:14,238 INFO SchemaUpdate:218 - HHH000102: Fetching database metadata 
    11:25:14,239 INFO SchemaUpdate:230 - HHH000396: Updating schema 
    11:25:14,426 INFO TableMetadata:66 - HHH000261: Table found: public.license_usage 
    11:25:14,426 INFO TableMetadata:67 - HHH000037: Columns: [dateinitial, usagequantity, dateend, id_user, id_package] 
    11:25:14,426 INFO TableMetadata:69 - HHH000108: Foreign keys: [fk_a7jlro2c6m3y8ofoxw0kajv78, fk_f342pmsmoib0j9osyh4fkxihm] 
    11:25:14,426 INFO TableMetadata:70 - HHH000126: Indexes: [license_usage_pkey] 
    11:25:14,535 INFO TableMetadata:66 - HHH000261: Table found: public.package 
    11:25:14,551 INFO TableMetadata:67 - HHH000037: Columns: [quantityoflicenses, vendordaemon, description, namepackage, id_package, version] 
    11:25:14,551 INFO TableMetadata:69 - HHH000108: Foreign keys: [] 
    11:25:14,551 INFO TableMetadata:70 - HHH000126: Indexes: [uk_atlshd2rl0yk0yfiw82t0vwc, package_pkey] 
    11:25:14,660 INFO TableMetadata:66 - HHH000261: Table found: public.users 
    11:25:14,660 INFO TableMetadata:67 - HHH000037: Columns: [unit, phone, pbrkey, name, location, id_user, email] 
    11:25:14,660 INFO TableMetadata:69 - HHH000108: Foreign keys: [] 
    11:25:14,660 INFO TableMetadata:70 - HHH000126: Indexes: [users_pkey] 
    11:25:14,660 INFO SchemaUpdate:267 - HHH000232: Schema update complete 
    11:25:15,066 DEBUG SQL:109 - 
     select 
      nextval ('hibernate_sequence') 
    Hibernate: 
     select 
      nextval ('hibernate_sequence') 
    11:25:15,269 DEBUG SQL:109 - 
     insert 
     into 
      package 
      (description, namePackage, quantityOfLicenses, vendorDaemon, version, id_package) 
     values 
      (?, ?, ?, ?, ?, ?) 
    Hibernate: 
     insert 
     into 
      package 
      (description, namePackage, quantityOfLicenses, vendorDaemon, version, id_package) 
     values 
      (?, ?, ?, ?, ?, ?) 
    11:25:15,285 DEBUG SQL:109 - 
     insert 
     into 
      license_usage 
      (id_package, id_user) 
     values 
      (?, ?) 
    Hibernate: 
     insert 
     into 
      license_usage 
      (id_package, id_user) 
     values 
      (?, ?) 
    11:25:15,286 INFO StatisticalLoggingSessionEventListener:275 - Session Metrics { 
     66504 nanoseconds spent acquiring 1 JDBC connections; 
     0 nanoseconds spent releasing 0 JDBC connections; 
     855522 nanoseconds spent preparing 3 JDBC statements; 
     7439438 nanoseconds spent executing 2 JDBC statements; 
     0 nanoseconds spent executing 0 JDBC batches; 
     0 nanoseconds spent performing 0 L2C puts; 
     0 nanoseconds spent performing 0 L2C hits; 
     0 nanoseconds spent performing 0 L2C misses; 
     88938261 nanoseconds spent executing 1 flushes (flushing a total of 1 entities and 1 collections); 
     0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections) 
    } 
    11:25:15,286 INFO AbstractBatchImpl:208 - HHH000010: On release of batch it still contained JDBC statements 
+0

你能後的堆棧跟蹤包括例外呢? – swinkler

+0

org.hibernate.TransientObjectException:對象引用未保存的瞬態實例 - 在刷新之前保存瞬態實例:schlumberger.sis.licenseControl.model.PbrUser – Eduardox23

回答

1

關於您的異常,這意味着:您想要保存一個包含用戶對象的包,而用戶對象本身並沒有被保存過。如果這會自動發生,您必須添加級聯 - 該示例僅使用「cascade all」作爲包 - 請檢查您真正需要的應用程序。

套餐:

@ManyToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL) 
    @JoinTable(name="license_usage", 
    joinColumns={@JoinColumn(name="id_package")}, 
    inverseJoinColumns={@JoinColumn(name="id_user")}) 
    private Collection<PbrUser> pbrUsers; 

用戶:

@ManyToMany(fetch=FetchType.LAZY, cascade = CascadeType.<WHAT YOU NEED>) 
    @JoinTable(name="license_usage", 
    [email protected](name="id_user"), 
    [email protected](name="id_package")) 
    private Collection<Package> packages; 
+0

我需要的是使用Package_Usage表保存與用戶關聯的包有這個協會的日期字段。我在每日日誌文件中提取這些信息。這是堅持的最好方法嗎? – Eduardox23

+0

使用Package @ManyToMany中的cascade = all,它應該自動保存所有關係,併爲此爲用戶。 – swinkler

+0

現在我可以保存第一組數據,但是當我嘗試保存與第一個包中的用戶相同的第二個包時,它會拋出異常。 實施例: 「P1」 CF57開始週一11/11 8:18 CWF3開始星期一11/11 9:30 「P2」 CSHC開始週一11/11 7:47 CF57開始星期一11/11 10點13 14:55:37733 WARN SqlExceptionHelper:144 - SQL錯誤:0,SQLSTATE:23505 14:55:37733 ERROR SqlExceptionHelper:146 - 錯誤:重複鍵值違反唯一約束 「uk_4faa4aeaeci5qobeiqqgoi5qf」 詳細信息:按鍵(pbrkey)=(CF57)已經存在。 – Eduardox23