使用Hibernate

时间:2015-05-04 16:15:26

标签: java hibernate postgresql many-to-many

我有两个班级,UserPackageUser可以包含多个Package,而Package可以与多个User相关联。所以我有一个多对多的关联。在我的数据库中,我有三个表:一个用于Users,一个用于Packages,以及Package-User表。

我已经测试了映射。我可以单独保存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",
        joinColumns=@JoinColumn(name="id_user"),
        inverseJoinColumns=@JoinColumn(name="id_package"))
        private Collection<Package> packages;

Process Function,我在其中设置与包关联的用户列表并传递给控制器​​以便保存到数据库中:

    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

1 个答案:

答案 0 :(得分:1)

关于您的异常,它意味着:您希望保存一个包,其中用户之前不保留用户对象本身。如果这应该自动发生,你必须添加级联 - 这个例子只是使用&#34; cascade all&#34;对于包裹 - 请检查您的应用程序真正需要的是什么。

包装:

$main-font: "Microsoft_YaHei247019", "Whitney SSm A", "Whitney SSm B", "Verdana"

用户:

@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;