Hibernate manytomany cascading - java

I got two entities, "project" and "employee", a project cointains 0, 1 or many employees and an employee can participate on 0, 1 or many projects.
So its a normal many to many relationship and a third table is required...lets call it "ProjectEmployee".
When i delete a project, the project itself should be deleted and the proper entry/entries in ProjectEmployee. But the employees should still exist.
Same for employee...so it should be possible to have many entries in project and in employee but not a single one in ProjectEmployee.
I hope its clear what I would like to have.
The problem is now that I donĀ“t know how the correct mapping(XML) should look like.
At the moment it is as follows:
Project:
<set name="employees" table="ProjectEmployee" cascade="save-update">
<key column="projectId" />
<many-to-many class="Employee" column="employeeId" />
</set>
<set name="modules" cascade="save-update,delete-orphan" fetch="select" lazy="true" inverse="true">
<key column="projectId" />
<one-to-many class="Modul" />
</set>
</class>
Employee
<class name="Employee">
<id name="id" type="long">
<generator class="sequence"></generator>
</id>
<property name="firstName" type="string">
<column name="firstName" />
</property>
<property name="lastName" type="string">
<column name="lastName" />
</property>
<property name="dateOfBirth" type="date">
<column name="dateOfBirth" />
</property>
<set name="logbookEntries" inverse="true" cascade="save-update,delete-orphan"
fetch="select" lazy="true">
<key column="employeeId" />
<one-to-many class="LogbookEntry" />
</set>
<set name="issues" inverse="true" cascade="save-update,delete-orphan"
fetch="select" lazy="true">
<key column="employeeId" />
<one-to-many class="Issue" />
</set>
<one-to-one name="address" class="Address" cascade="save-update, delete" />
<set name="projects" table="ProjectEmployee" inverse="true"
cascade="save-update">
<key column="employeeId" />
<many-to-many class="Project" column="projectId"/>
</set>
<joined-subclass name="PermanentEmployee">
<key column="id" />
<property name="salary" />
</joined-subclass>
<joined-subclass name="TemporaryEmployee">
<key column="id" />
<property name="hourlyRate"></property>
<property name="renter"></property>
<property name="startDate"></property>
<property name="endDate"></property>
</joined-subclass>
</class>
At the moment, I get an Exception when I would like to delete an employee.
org.hibernate.exception.ConstraintViolationException
Thats because I didnt configure "cascade:delete"!
I hope you can help me.

Related

What is the meaning of discriminator-value in Hibernate mapping file?

<class name="admin.model.OrganizationUnit" table="ORGANIZATION_UNIT" discriminator-value="admin.model.OrganizationUnit" dynamic-update="true">
<id name="ObjectId" type="string" column="object_id">
<generator class="assigned"/>
</id>
<discriminator column="discriminator"/>
<property name="ObjectType" type="string">
<column name="ObjectType" sql-type="varchar2(255)" not-null="true"/>
</property>
<subclass name="admin.model.DmSystem" discriminator-value="admin.model.DmSystem" dynamic-update="true">
<set name="ChildOrgs" lazy="true" table="ORGANIZATION_UNIT" where="ou_type_code='CWORG'">
<key column="system_org_id"/>
<one-to-many class="Dm.bizcomponent.admin.model.OrganizationUnit"/>
</set>
<set name="SystemAdminAccessGroup" lazy="true" inverse="true" table="CWGROUP" where="group_type_code='SYSTEM_ADMINACCESS'">
<key column="owner_id"/>
<one-to-many class="admin.model.Group"/>
</set>
</subclass>
</class>
Here is the mapping code
In the above code there is one parent Class OrganizationUnit with two subclass
The discriminator-value is used to determine the class type of the entity subclass type associated with a given database row entry in the base class database table.

Hibernate many-to-one

I have to tables Usuario_tbl and RolUsuario_tbl. I generate java model with hibernate reverse engineering having this .hbm.xml
<hibernate-mapping>
<class name="co.ejemplo.modelo.UsuarioTbl" table="usuario_tbl" catalog="structse_db">
<id name="idUsuario" type="java.lang.Integer">
<column name="id_usuario" />
<generator class="identity" />
</id>
<property name="login" type="string">
<column name="login" length="50" not-null="true" unique="true" />
</property>
<property name="clave" type="string">
<column name="clave" not-null="true" />
</property>
<property name="habilitado" type="byte">
<column name="habilitado" not-null="true" />
</property>
<property name="fechaAlta" type="timestamp">
<column name="fecha_alta" length="19" />
</property>
<property name="fechaBaja" type="timestamp">
<column name="fecha_baja" length="19" />
</property>
<set name="rolUsuarioTbls" table="rol_usuario_tbl" inverse="true" lazy="true" fetch="select">
<key>
<column name="login" not-null="true" />
</key>
<one-to-many class="co.ejemplo.modelo.RolUsuarioTbl" />
</set>
</class>
</hibernate-mapping>
and
<hibernate-mapping>
<class name="co.ejemplo.modelo.RolUsuarioTbl" table="rol_usuario_tbl" catalog="structse_db">
<id name="idUsuarioRol" type="java.lang.Integer">
<column name="id_usuario_rol" />
<generator class="identity" />
</id>
<many-to-one name="usuarioTbl" class="co.ejemplo.modelo.UsuarioTbl" fetch="select">
<column name="login" not-null="true" />
</many-to-one>
<property name="rol" type="string">
<column name="rol" length="50" not-null="true" />
</property>
</class>
</hibernate-mapping>
When I try to save one RolUsuarioTbl using getHibernateTemplate().save(rolUsuarioTbl) hibernate tells me that needs all the UsuarioTbl properties but I only has setting the login in UsuarioTbl.
How can I save RolUsuarioTbl having only login property in UsuarioTbl?
Many to one relations must be by the code of both tables, otherwise hibernate will not recognize the children of the parent table.

Hibernate org.hibernate.MappingException... an associon ..to unmapped class- Many toMany

I have auto generated the code using netbeans to create a Hibernate configuration; so I have two tables mapped like this (Many-to-Many) :
<hibernate-mapping auto-import="true">
<class name="com.antoiovi.jobprograms.entity.Roles" table="roles" catalog="jobprograms">
<id name="rolesName" type="string">
<column name="roles_name" length="20" />
<generator class="assigned" />
</id>
<set name="userses" table="users_roles" inverse="true" lazy="false" fetch="select" cascade="all">
<key>
<column name="role_name" length="20" not-null="true" />
</key>
<many-to-many entity-name="com.antoiovi.jobprograms.entity.Users">
<column name="user_name" length="15" not-null="true" />
</many-to-many>
</set>
</class>
<hibernate-mapping auto-import="true">
<class name="com.antoiovi.jobprograms.entity.Users" table="users" catalog="jobprograms">
<id name="idusers" type="java.lang.Integer">
<column name="idusers" />
<generator class="identity" />
</id>
<property name="userName" type="string">
<column name="user_name" length="15" not-null="true" unique="true" />
</property>
<property name="userPass" type="string">
<column name="user_pass" length="15" not-null="true" />
</property>
<property name="firstName" type="string">
<column name="first_name" length="20" />
</property>
<property name="lastName" type="string">
<column name="last_name" length="25" />
</property>
<set name="roleses" table="users_roles" inverse="true" lazy="false" fetch="select" cascade="all">
<key>
<column name="user_name" length="15" not-null="true" />
</key>
<many-to-many entity-name="com.antoiovi.jobprograms.entity.Roles">
<column name="role_name" length="20" not-null="true" />
</many-to-many>
</set>
<set name="jobprograms" table="jobprogram" inverse="true" lazy="false" fetch="select" cascade="all">
<key>
<column name="users_idusers" not-null="true" />
</key>
<one-to-many class="com.antoiovi.jobprograms.entity.Jobprogram" />
</set>
</class>
I have made some modification as you can see above (auto-import=true, lazy=false), cause i have the error message
rg.hibernate.MappingException: An association from the table users_roles refers to an unmapped class: com.antoiovi.jobprograms.entity.Roles
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1824)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1756)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1423)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
The config file is
<hibernate-configuration>
org.hibernate.dialect.MySQLDialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/jobprograms?zeroDateTimeBehavior=convertToNull
jobprograms_ad
xxxxx
thread
true
org.hibernate.hql.classic.ClassicQueryTranslatorFactory
true
the classes have refernce like this :
'#ManyToMany(fetch=FetchType.LAZY, mappedBy="roleses")
public Set<Users> getUserses() {
return this.userses;
} '
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name="users_roles", catalog="jobprograms", joinColumns = {
#JoinColumn(name="user_name", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="role_name", nullable=false, updatable=false) })
public Set<Roles> getRoleses() {
return this.roleses;
}
wHEN RUNNING I HAVE THE ERROR org.hibernate.exception.SQLGrammarException, and in fact the entiti is loaded, but the set<> not..,
When testing the error is
org.hibernate.MappingException: An association from the table users_roles refers to an unmapped class: com.antoiovi.jobprograms.entity.Roles, and the HSQL ar not executed.
I tried to look in others post but i couldn't find an answer. Can anybody help me?
In config file the entities are all declared;
I think yhe promlem is in the mapping :
e <set name="roleses" table="users_roles" inverse="false" lazy="true" fetch="select" >
<key >
<column name="user_name" length="15" not-null="true" />
</key>
<many-to-many entity-name="test.Roles" property-ref="rolesName">
<column name="role_name" length="20" not-null="true" />
</many-to-many>
</set>
<set name="jobprograms" table="jobprogram" inverse="true" lazy="true" fetch="select">
<key>
<column name="users_idusers" not-null="true" />
</key>
<one-to-many class="test.Jobprogram" />
</set>
and
enter <class name="test.Roles" table="roles" catalog="jobprograms">
<id name="rolesName" type="string">
<column name="roles_name" length="20" />
<generator class="assigned" />
</id>
<set name="userses" table="users_roles" inverse="true" lazy="true" fetch="select">
<key property-ref="rolesName">
<column name="role_name" length="20" not-null="true" />
</key>
<many-to-many entity-name="test.Users" property-ref="userName">
<column name="user_name" length="15" not-null="true" />
</many-to-many>
</set>
</class>
....
this error
org.hibernate.MappingException: An association from the table users_roles refers to an unmapped class: com.antoiovi.jobprograms.entity.Roles
comes when hibernate configuration dont know about entity(Roles) mapping , either you have missed introducing enitity Roles to the hibernate configuration or you have not used correct name , please check configuraiton file and included com.antoiovi.jobprograms.entity.Roles as resourse
I think to have resolved the problem. Actually the proble are unmapped entities. But this happens because the database is not 'well formed'. Indeed the database ha 3 table users, users_roles, roles; the table roles has only one column as primarykey (varchar),and the table user_roles refers to it from its column user_roles; when forword enginering the ide (in the case netbeans) creates only 2 entities: 'Users', and 'Roles'; So i have re-designed the schema putting some virtual primary key, and creating unique constaint instead. Now i have 3 entities : Users,UserRoles, and Roles.

Hibernate java web application

I am working on a java JSP webapplication that uses the hibernate framework.
I am a total beginner with JSP/hibernate, and I can't seem to get hibernate to work.
I have followed this tutorial: https://netbeans.org/kb/docs/web/hibernate-webapp.html
It all worked. I used xampp with phpmyadmin, and I could execute HQL query's through the hibernate.cfg.xml file.
Then I was trying the same thing with the database I am using for the web application. Followed all steps and went through all the wizards. But I can't execute HQL query's.
the following error is given:
org.hibernate.MappingException: An association from the table campingsperfestival refers to an unmapped class: festivalOverview.Campings
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1252)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1170)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
I followed the Hibernate Mapping Files and POJOs from Database wizard, and it generated a .java and .hbm.xml file for all tables in the database except for one table: the 'campingsperfestival' table. I've done the wizard again a few times and started it all over but it still doesn't generate the .java and .hbm.xml file for the 'campingsperfestival' table.
The 'campingsperfestival' table is a table with 2 id's that both have a foreign key. There are festivals and campings that both have ID's, the 'campingsperfestival' matches those 2 id's in one table.
Campings.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20-apr-2013 12:04:37 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="festivalOverview.Campings" table="campings" catalog="groep11_festivals">
<id name="campId" type="java.lang.Integer">
<column name="camp_id" />
<generator class="identity" />
</id>
<property name="campAdres" type="string">
<column name="camp_adres" not-null="true" />
</property>
<property name="campCap" type="int">
<column name="camp_cap" not-null="true" />
</property>
<set name="festivalses" inverse="true" table="campingsperfestival">
<key>
<column name="camp_id" not-null="true" />
</key>
<many-to-many entity-name="festivalOverview.Festivals">
<column name="fest_id" not-null="true" />
</many-to-many>
</set>
<set name="facpercamps" inverse="true">
<key>
<column name="camp_id" not-null="true" />
</key>
<one-to-many class="festivalOverview.Facpercamp" />
</set>
</class>
</hibernate-mapping>
Festivals.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20-apr-2013 12:04:37 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="festivalOverview.Festivals" table="festivals" catalog="groep11_festivals">
<id name="festId" type="java.lang.Integer">
<column name="fest_id" />
<generator class="identity" />
</id>
<property name="festNaam" type="string">
<column name="fest_naam" length="100" not-null="true" />
</property>
<property name="festLocatie" type="string">
<column name="fest_locatie" length="200" not-null="true" />
</property>
<property name="festDatum" type="date">
<column name="fest_datum" length="10" not-null="true" />
</property>
<property name="festDuur" type="byte">
<column name="fest_duur" not-null="true" />
</property>
<set name="ticketses" inverse="true">
<key>
<column name="fest_id" not-null="true" />
</key>
<one-to-many class="festivalOverview.Tickets" />
</set>
<set name="bandsperfestivals" inverse="true">
<key>
<column name="fest_id" not-null="true" />
</key>
<one-to-many class="festivalOverview.Bandsperfestival" />
</set>
<set name="campingses" inverse="false" table="campingsperfestival">
<key>
<column name="fest_id" not-null="true" />
</key>
<many-to-many entity-name="festivalOverview.Campings">
<column name="camp_id" not-null="true" />
</many-to-many>
</set>
<set name="tickettypesperfestivals" inverse="true">
<key>
<column name="fest_id" not-null="true" />
</key>
<one-to-many class="festivalOverview.Tickettypesperfestival" />
</set>
</class>
</hibernate-mapping>
I'm only a beginner with hibernate and really don't know how to solve this problem. Any help is greatly appreciated!
I assume campingsperfestival is a join table between two classes, Campings and Festival? Have you defined both these classes and their mapping?
The error you have there is saying it can't create campingsperfestival because it is referring to Campings, which is not defined as as hibernate class. So make sure Campings is defined and you have the mapping correct.
If you are still unclear we may be able to help more if you show the java/mappings you have for campings and festival.
As an aside, if this is a new project you are embarking on, I would really recommend using annotation based hibernate classes. You may also find it a more productive learning experience to create your hibernate entity classes yourself rather than using netbeasns - but that's down to personal preference.

org.hibernate.exception.MappingException or ConstraintViolation

I am using hibernate 4.1.9. I have Users, and the Users have a list of Accounts, and Accounts have list of Transactions. Here is my hbm.xml
<?xml version="1.0"?>
<class name="User" table="users">
<id name="userId" column="userid">
<generator class="increment"/>
</id>
<property name="username" column="username" not-null="true"/>
<property name="password" column="password" not-null="true"/>
<property name="registerDate" type="timestamp" column="register_date"/>
<list name="accounts" table="accounts" inverse="true" cascade="all">
<key column="userid" not-null="true"/>
<index column="accountid"/>
<one-to-many class="com.joe.data.Account"/>
</list>
</class>
<class name="Account" table="accounts">
<id name="accountId" column="accountid">
<generator class="increment"/>
</id>
<property name="balance" type="big_decimal" column="balance"/>
<property name="lastModified" type="timestamp" column="last_modified"/>
<list name="txns" table="transactions" inverse="true" cascade="all">
<key column="accountId" not-null="true"/>
<index column="transactionId"/>
<one-to-many class="com.joe.data.Transaction"/>
</list>
<many-to-one name="userId" class="User" column="userid" not-null="true"
unique="true" cascade="all"/>
<many-to-one name="accountType" class="AccountType" column="account_type"
not-null="true" cascade="all" unique="true" />
</class>
<class name="Transaction" table="transactions">
<id name="transactionId" column="transactionid">
<generator class="increment"/>
</id>
<property name="description" column="description"/>
<property name="amount" type="big_decimal" column="amount"/>
<property name="dateAdded" column="date_added"/>
<property name="reoccuring" type="numeric_boolean" column="reoccuring"/>
<many-to-one name="category" class="Category" column="category"
not-null="true" cascade="all" unique="true" />
</class>
<class name="Category" table="categories">
<id name="categoryId" column="categoryid"/>
<property name="categoryName" column="categoryname" not-null="true"/>
</class>
<class name="AccountType" table="account_types">
<id name="accountType" column="account_type"/>
<property name="accountName" column="name"/>
</class>
If I leave inverse="true" on the list of accounts (in the User) I get the ConstraintViolationException because the userid is not getting put in the insert query. If I take inverse="true" off of the list of accounts, I get org.hibernate.MappingException: Repeated column in mapping for entity: com.joe.data.Account column: accountid (should be mapped with insert="false" update="false")
To clarify lowercase names are database columns names, camel case are class variable names. I know Transaction class isn't working quite right yet, but if I could get the Accounts to insert I could do the same thing to get the Transactions to insert.
Edit: I added the many-to-one on the Account class and now I am getting another exception where hibernate is complaining about missing a getter for userId in com.joe.data.Account
In order to get inverse="true" work, you need to define many-to-one for User in Account and for Account in Transaction class and mappings.

Categories

Resources