我有兩個類,User
和Package
。 A User
可以有多個Package
和Package
可以有多個User
與之關聯。所以我有一個多對多的關聯。在我的數據庫中,我有三個表:一個用於用戶,一個用於軟件包和Package-User表。使用Hibernate保存在@ManyToMany關聯
我已經測試了映射。我可以單獨保存User
和Package
,但是當我嘗試保存包含與其關聯的用戶列表的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
你能後的堆棧跟蹤包括例外呢? – swinkler
org.hibernate.TransientObjectException:對象引用未保存的瞬態實例 - 在刷新之前保存瞬態實例:schlumberger.sis.licenseControl.model.PbrUser – Eduardox23