Hibernate insert query - java
During insertion in hibernate query i'm passing some fields as table class objects which i've mapped to corresponding tables, The query works fine but the query is becoming too large because each of these mapped objects are getting updated individually to their corresponding tables.
Can anyone please tell me whether this is the correct way of insertion and also why i'm getting those update queries.
Hibernate: insert into ortms.tool_modified_his_tbl (tool_desc, old_tool_desc, connec1, old_connec1, connec2, old_connec2, landed_cost, old_landed_cost, acqui_date, old_acqui_date, manuf_date, old_manuf_date, price_ref, old_price_ref, op_rate_cost, old_op_rate_cost, stb_rate_cost, old_stb_rate_cost, day_rate1_cost, old_day_rate1_cost, day_rate2_cost, old_day_rate2_cost, packermilling_cost, old_packermilling_cost, sale_value, old_sale_value, status, created_date, modified_date, tool_id, tool_modi_reas_id, tool_modi_usr_id, supplier_id, old_supplier_id, tc_status_id, old_tc_status_id, pricing_type_id, old_pricing_type_id, old_ownership_id, ownership_id, unit_id, old_unit_id, branch_id, old_branch_id, reta_tool_choice_id, old_reta_tool_choice_id, non_ser_tol_cho_id, old_non_ser_tol_cho_id, charge_by_id, old_charge_by_id, size_range_id, old_size_range_id, rack_id, old_rack_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update ortms.master2_tool_master set tool_id=?, tool_desc=?, connec1=?, connec2=?, landed_cost=?, acqui_date=?, manuf_date=?, price_ref=?, op_rate_cost=?, stb_rate_cost=?, day_rate1_cost=?, day_rate2_cost=?, packermilling_cost=?, sale_value=?, uploaded_filename=?, uploaded_file=?, status=?, created_date=?, modified_date=?, supplier_id=?, tc_status_id=?, pricing_type_id=?, unit_id=?, reta_tool_choice_id=?, non_ser_tol_cho_id=?, branch_id=?, charge_by_id=?, size_range_id=?, rack_id=?, ownership_id=? where id=?
Hibernate: update ortms.table_users set user_code=?, username=?, password=?, first_name=?, last_name=?, status=?, created_date=?, modified_date=?, dept_id=?, branch_id=? where id=?
Hibernate: update ortms.table_choice_select set choice_name=?, status=?, created_date=?, modified_date=? where id=?
Hibernate: update ortms.master2_toolmast_chargeby set chargeby=?, status=?, created_date=?, modified_date=? where id=?
Hibernate: update ortms.master2_sizerange set size_code=?, size_range=?, status=?, created_date=?, modified_date=?, grp_lev3_id=? where id=?
Hibernate: update ortms.master2_group_level3 set grp_lev3_name=?, grp_lev3_desc=?, created_date=?, modified_date=?, status=?, grp_lev2_id=? where id=?
Hibernate: update ortms.master2_group_level2 set grp_lev2_name=?, grp_lev2_desc=?, created_date=?, modified_date=?, status=?, grp_lev1_id=? where id=?
After calling action: master2.toolmaster.ToolMaster Time taken: 1234 ms
UPDATION 2
ToolModifiedHisTbl.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 Mar 2, 2013 9:29:05 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="mappingfiles.ToolModifiedHisTbl" table="tool_modified_his_tbl" catalog="ortms">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="toolDesc" type="string">
<column name="tool_desc" length="65535" />
</property>
<property name="oldToolDesc" type="string">
<column name="old_tool_desc" length="65535" />
</property>
<property name="connec1" type="string">
<column name="connec1" length="60" />
</property>
<property name="oldConnec1" type="string">
<column name="old_connec1" length="60" />
</property>
<property name="connec2" type="string">
<column name="connec2" length="60" />
</property>
<property name="oldConnec2" type="string">
<column name="old_connec2" length="60" />
</property>
<property name="landedCost" type="string">
<column name="landed_cost" length="20" />
</property>
<property name="oldLandedCost" type="string">
<column name="old_landed_cost" length="20" />
</property>
<property name="acquiDate" type="date">
<column name="acqui_date" length="10" />
</property>
<property name="oldAcquiDate" type="date">
<column name="old_acqui_date" length="10" />
</property>
<property name="manufDate" type="date">
<column name="manuf_date" length="10" />
</property>
<property name="oldManufDate" type="date">
<column name="old_manuf_date" length="10" />
</property>
<property name="priceRef" type="string">
<column name="price_ref" length="20" />
</property>
<property name="oldPriceRef" type="string">
<column name="old_price_ref" length="20" />
</property>
<property name="opRateCost" type="string">
<column name="op_rate_cost" length="20" />
</property>
<property name="oldOpRateCost" type="string">
<column name="old_op_rate_cost" length="20" />
</property>
<property name="stbRateCost" type="string">
<column name="stb_rate_cost" length="20" />
</property>
<property name="oldStbRateCost" type="string">
<column name="old_stb_rate_cost" length="20" />
</property>
<property name="dayRate1Cost" type="string">
<column name="day_rate1_cost" length="20" />
</property>
<property name="oldDayRate1Cost" type="string">
<column name="old_day_rate1_cost" length="20" />
</property>
<property name="dayRate2Cost" type="string">
<column name="day_rate2_cost" length="20" />
</property>
<property name="oldDayRate2Cost" type="string">
<column name="old_day_rate2_cost" length="20" />
</property>
<property name="packermillingCost" type="string">
<column name="packermilling_cost" length="20" />
</property>
<property name="oldPackermillingCost" type="string">
<column name="old_packermilling_cost" length="20" />
</property>
<property name="saleValue" type="string">
<column name="sale_value" length="20" />
</property>
<property name="oldSaleValue" type="string">
<column name="old_sale_value" length="20" />
</property>
<property name="status" type="string">
<column name="status" length="20" />
</property>
<property name="createdDate" type="timestamp">
<column name="created_date" length="19" />
</property>
<property name="modifiedDate" type="timestamp">
<column name="modified_date" length="19" />
</property>
<many-to-one class="mappingfiles.Master2ToolMaster" unique="true" name="toolId" column="tool_id" cascade="all" />
<many-to-one class="mappingfiles.TableModifiedReason" unique="true" name="toolModiReasId" column="tool_modi_reas_id" cascade="all" />
<many-to-one class="mappingfiles.TableUsers" unique="true" name="toolModiUsrId" column="tool_modi_usr_id" cascade="all" />
<many-to-one class="mappingfiles.TableSupplier" unique="true" name="supplierId" column="supplier_id" cascade="all" />
<many-to-one class="mappingfiles.TableSupplier" unique="true" name="oldSupplierId" column="old_supplier_id" cascade="all" />
<many-to-one class="mappingfiles.TableToolContractStatus" unique="true" name="tcStatusId" column="tc_status_id" cascade="all" />
<many-to-one class="mappingfiles.TableToolContractStatus" unique="true" name="oldTcStatusId" column="old_tc_status_id" cascade="all" />
<many-to-one class="mappingfiles.Master2PriceType" unique="true" name="pricingTypeId" column="pricing_type_id" cascade="all" />
<many-to-one class="mappingfiles.Master2PriceType" unique="true" name="oldPricingTypeId" column="old_pricing_type_id" cascade="all" />
<many-to-one class="mappingfiles.TableOwnership" unique="true" name="oldOwnershipId" column="old_ownership_id" cascade="all" />
<many-to-one class="mappingfiles.TableOwnership" unique="true" name="ownershipId" column="ownership_id" cascade="all" />
<many-to-one class="mappingfiles.Master2UnitMaster" unique="true" name="unitId" column="unit_id" cascade="all" />
<many-to-one class="mappingfiles.Master2UnitMaster" unique="true" name="oldUnitId" column="old_unit_id" cascade="all" />
<many-to-one class="mappingfiles.TableBranchesCompany" unique="true" name="branchId" column="branch_id" cascade="all" />
<many-to-one class="mappingfiles.TableBranchesCompany" unique="true" name="oldBranchId" column="old_branch_id" cascade="all" />
<many-to-one class="mappingfiles.TableChoiceSelect" unique="true" name="retaToolChoiceId" column="reta_tool_choice_id" cascade="all" />
<many-to-one class="mappingfiles.TableChoiceSelect" unique="true" name="oldRetaToolChoiceId" column="old_reta_tool_choice_id" cascade="all" />
<many-to-one class="mappingfiles.TableChoiceSelect" unique="true" name="nonSerTolChoId" column="non_ser_tol_cho_id" cascade="all" />
<many-to-one class="mappingfiles.TableChoiceSelect" unique="true" name="oldNonSerTolChoId" column="old_non_ser_tol_cho_id" cascade="all" />
<many-to-one class="mappingfiles.Master2ToolmastChargeby" unique="true" name="chargeById" column="charge_by_id" cascade="all" />
<many-to-one class="mappingfiles.Master2ToolmastChargeby" unique="true" name="oldChargeById" column="old_charge_by_id" cascade="all" />
<many-to-one class="mappingfiles.Master2Sizerange" unique="true" name="sizeRangeId" column="size_range_id" cascade="all" />
<many-to-one class="mappingfiles.Master2Sizerange" unique="true" name="oldSizeRangeId" column="old_size_range_id" cascade="all" />
<many-to-one class="mappingfiles.Master2Racks" unique="true" name="rackId" column="rack_id" cascade="all" />
<many-to-one class="mappingfiles.Master2Racks" unique="true" name="oldRackId" column="old_rack_id" cascade="all" />
</class>
</hibernate-mapping>
TableUsers.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 Jan 13, 2013 4:26:04 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="mappingfiles.TableUsers" table="table_users" catalog="ortms">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="userCode" type="string">
<column name="user_code" length="60" />
</property>
<property name="username" type="string">
<column name="username" length="50" />
</property>
<property name="password" type="string">
<column name="password" length="50" />
</property>
<property name="firstName" type="string">
<column name="first_name" length="60" />
</property>
<property name="lastName" type="string">
<column name="last_name" length="60" />
</property>
<property name="status" type="string">
<column name="status" length="20" />
</property>
<property name="createdDate" type="timestamp">
<column name="created_date" length="19" />
</property>
<property name="modifiedDate" type="timestamp">
<column name="modified_date" length="19" />
</property>
<many-to-one class="mappingfiles.TableDepartments" unique="true" name="deptId" column="dept_id" cascade="all" />
<many-to-one class="mappingfiles.TableBranchesCompany" unique="true" name="branchId" column="branch_id" cascade="all" />
</class>
</hibernate-mapping>
UPDATION 3
i've removed cascade="all" attribute from all mappings....now i'm getting one update rest all clear
Hibernate: insert into ortms.tool_modified_his_tbl (tool_desc, old_tool_desc, connec1, old_connec1, connec2, old_connec2, landed_cost, old_landed_cost, acqui_date, old_acqui_date, manuf_date, old_manuf_date, price_ref, old_price_ref, op_rate_cost, old_op_rate_cost, stb_rate_cost, old_stb_rate_cost, day_rate1_cost, old_day_rate1_cost, day_rate2_cost, old_day_rate2_cost, packermilling_cost, old_packermilling_cost, sale_value, old_sale_value, status, created_date, modified_date, tool_id, tool_modi_reas_id, tool_modi_usr_id, supplier_id, old_supplier_id, tc_status_id, old_tc_status_id, pricing_type_id, old_pricing_type_id, old_ownership_id, ownership_id, unit_id, old_unit_id, branch_id, old_branch_id, reta_tool_choice_id, old_reta_tool_choice_id, non_ser_tol_cho_id, old_non_ser_tol_cho_id, charge_by_id, old_charge_by_id, size_range_id, old_size_range_id, rack_id, old_rack_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update ortms.master2_tool_master set tool_id=?, tool_desc=?, connec1=?, connec2=?, landed_cost=?, acqui_date=?, manuf_date=?, price_ref=?, op_rate_cost=?, stb_rate_cost=?, day_rate1_cost=?, day_rate2_cost=?, packermilling_cost=?, sale_value=?, uploaded_filename=?, uploaded_file=?, status=?, created_date=?, modified_date=?, supplier_id=?, tc_status_id=?, pricing_type_id=?, unit_id=?, reta_tool_choice_id=?, non_ser_tol_cho_id=?, branch_id=?, charge_by_id=?, size_range_id=?, rack_id=?, ownership_id=? where id=?
The unwanted updates come from the "cascade all" settings. You may want to configure it properly according to your needs. For example, have a look here: http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/
Use dynamic-insert=true and dynamic-update=true at class level
After this your query will be short. It will insert and update only the specified not null values.
Related
How to select multi tables with WHERE clause
I want to get id and name of user, who have mhId = "AAA" (mhId is a column in table User_MonHoc. In User_MonHoc, mhid + user_id are primary key). Table User: <hibernate-mapping> <class name="entites.User" table="user" catalog="bthibernate" optimistic-lock="version"> <id name="username" type="string"> <column name="username" length="100" /> <generator class="assigned" /> </id> <property name="password" type="string"> <column name="password" length="100" not-null="true" /> </property> <property name="note" type="byte"> <column name="note" not-null="true" /> </property> <property name="name" type="string"> <column name="name" length="100" not-null="true" /> </property> <set name="userMonhocs" table="user_monhoc" inverse="true" lazy="true" fetch="select"> <key> <column name="user_id" length="100" not-null="true" /> </key> <one-to-many class="entites.UserMonhoc" /> </set> </class> Table User_MonHoc <hibernate-mapping> <class name="entites.UserMonhoc" table="user_monhoc" catalog="bthibernate" optimistic-lock="version"> <composite-id name="id" class="entites.UserMonhocId"> <key-property name="userId" type="string"> <column name="user_id" length="100" /> </key-property> <key-property name="mhId" type="string"> <column name="mh_id" length="100" /> </key-property> </composite-id> <many-to-one name="monhoc" class="entites.Monhoc" update="false" insert="false" fetch="select"> <column name="mh_id" length="100" not-null="true" /> </many-to-one> <many-to-one name="user" class="entites.User" update="false" insert="false" fetch="select"> <column name="user_id" length="100" not-null="true" /> </many-to-one> <property name="thoigianDk" type="timestamp"> <column name="thoigian_dk" length="19" not-null="true" /> </property> </class> I want to get id and name of user, who have mhId = "AAA" (mhId is a column in table User_MH). Thank you!
You should join User and User_MH table in a SQL or HQL query. set alias to User_MH in your query o access User_MH table in where clause: SQL : SELECT tbl_user.useranme,tbl_user_mh.user_id FROM User AS tbl_user INNER JOIN User_MH AS tbl_user_mh ON tbl_user.id=tbl_user_mh.user_id WHERE tbl_user_mh.mhdl = 'AAA
Hibernate (XML mapping) insert fail
I'm trying to insert a new register but when Hibernate creates the insert it doesn't put the FK value. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="ar.com.grupo1.entity.Turno" table="Turno"> <id name="numeroTurno" type="int"> <column name="Id_Turno" /> <generator class="identity" /> </id> <property name="nombrePaciente" type="string"> <column name="Nombre" length="60" not-null="true" /> </property> <property name="apellidoPaciente" type="string"> <column name="Apellido" length="60" not-null="true" /> </property> <property name="planMedico" type="string"> <column name="PlanMedico" length="30" not-null="true" /> </property> <property name="fechaLlegada" type="string"> <column name="FechaHoraLlegada" length="60" /> </property> <property name="fechaAtencion" type="string"> <column name="FechaHoraAtencion" length="60" /> </property> <property name="importe" type="float"> <column name="Importe" /> </property> <property name="observaciones" type="string"> <column name="Observaciones" length="250" /> </property> <one-to-one name="prestador" class="ar.com.grupo1.entity.Prestador"></one-to-one> <one-to-one name="practica" class="ar.com.grupo1.entity.Practica"></one-to-one> <one-to-one name="socio" class="ar.com.grupo1.entity.Socio" constrained="true"></one-to-one> </class> </hibernate-mapping> On the insert is there isn't the Id_Socio value. INFO [STDOUT] Hibernate: insert into Turno (Nombre, Apellido, PlanMedico, FechaHoraLlegada, FechaHoraAtencion, Importe, Observaciones) values (?, ?, ?, ?, ?, ?, ?) WARN [JDBCExceptionReporter] SQL Error: 515, SQLState: 23000 ERROR [JDBCExceptionReporter] Værdien NULL kan ikke indsættes i kolonnen 'Id_Socio', tabellen 'grupo1.dbo.Turno'. Kolonnen tillader ikke null-værdier. INSERT kan ikke udføres. UPDATE I've already checked that the Socio's, Practica's, and Prestador's ID exists in the database. I'm giving to Turnos all these classes as attributes, it gets them correctly but at the time it does the Insert operation, is not inserting the FK values.
org.hibernate.QueryException: could not resolve property - mapping issue
I am posting this question because all the other questions with the same title was not able to resolve my issue. I have the following table: CREATE TABLE CONTRACT_DB_AGREEMENT ( AGREEMENT_CODE VARCHAR2(50), COM_CONTRACT_CODE VARCHAR2(15), AGREEMENT_TYPE VARCHAR2(20), EXPIRE_DATE TIMESTAMP(6), SIGNATORY_USER_NAME NVARCHAR2(150), SIGNATORY_NAME NVARCHAR2(50), ORIGINATOR_USER_NAME NVARCHAR2(150), ORIGINATOR_NAME NVARCHAR2(50), DATE_CREATED TIMESTAMP(6), CREATED_BY NVARCHAR2(150), LAST_UPDATE_DATE TIMESTAMP(6), LAST_UPDATED_BY NVARCHAR2(150), CONSTRAINT CONTRACT_DB_AGREEMENT_PK PRIMARY KEY (AGREEMENT_CODE), CONSTRAINT CONTRACT_DB_AGREEMENT_FK1 FOREIGN KEY(COM_CONTRACT_CODE) REFERENCES CONTRACTS (CONTRACT_CODE) ); In the HBM file, I have this: <id name="agreementCode" type="string"> <column name="AGREEMENT_CODE" length="50" /> <generator class="assigned" /> </id> <property name="agreementType" type="string"> <meta attribute="scope-field">#Length(min = 0, max = 20) private</meta> <column name="AGREEMENT_TYPE" length="20" /> </property> <property name="expireDate" type="timestamp"> <column name="EXPIRE_DATE" sql-type="timestamp" /> </property> <property name="signatoryUserName" type="string"> <meta attribute="scope-field">#Length(min=0, max=150) private</meta> <column name="SIGNATORY_USER_NAME" length="150" /> </property> <property name="signatoryName" type="string"> <meta attribute="scope-field">#Length(min=0, max=50) private</meta> <column name="SIGNATORY_NAME" length="50" /> </property> <property name="originatorUserName" type="string"> <meta attribute="scope-field">#Length(min=0, max=150) private</meta> <column name="ORIGINATOR_USER_NAME" length="150" /> </property> <property name="originatorName" type="string"> <meta attribute="scope-field">#Length(min=0, max=50) private</meta> <column name="ORIGINATOR_NAME" length="50" /> </property> <property name="dateCreated" type="timestamp"> <column name="DATE_CREATED" sql-type="timestamp" /> </property> <property name="createdBy" type="string"> <meta attribute="scope-field">#Length(min=0, max=150) private</meta> <column name="CREATED_BY" length="150" /> </property> <property name="lastUpdateDate" type="timestamp"> <column name="LAST_UPDATE_DATE" sql-type="timestamp" /> </property> <property name="lastUpdatedBy" type="string"> <meta attribute="scope-field">#Length(min=0, max=150) private</meta> <column name="LAST_UPDATED_BY" length="150" /> </property> <set name="contractDBAttachments" inverse="true" cascade="save-update"> <key> <column name="AGREEMENT_CODE" /> </key> <one-to-many class="ContractDBAttachment" /> </set> <set name="contractDBNotes" inverse="true" cascade="save-update"> <key> <column name="AGREEMENT_CODE" /> </key> <one-to-many class="ContractDBNote" /> </set> <many-to-one name="contract" class="Contract"> <meta attribute="scope-field">#Length(min = 0, max = 15) private</meta> <column name="COM_CONTRACT_CODE" length="15"/> </many-to-one> I try to run this HQL: String sql = "SELECT a FROM ContractDBAgreement a WHERE a.comContractCode = ?"; params.add(contractCode); List<ContractDBAgreement> resultList = DaoManager.getDao(ContractDBAgreement.class).searchBySql(sql, params.toArray()); But I get the following error: org.hibernate.QueryException: could not resolve property: comContractCode of: com.company.entity.ContractDBAgreement [SELECT a FROM com.company.entity.ContractDBAgreement a WHERE a.comContractCode = ?] I appreciate any help on this please. Thank you! UPDATE/EDIT I updated the field names. I tried hiding the company name I work for and think I altered the code too much. I put it closer to what it actually is. Pretty much, the column is called "COM_CONTRACT_CODE", not just "CONTRACT_CODE"
I got this to work. I had to change the <many-to-one> section to the following: <property name="comContractCode" type="string"> <meta attribute="scope-field">#Length(min = 0, max = 15) private</meta> <column name="COM_CONTRACT_CODE" length="15"/> </property> <many-to-one name="contract" column="COM_CONTRACT_CODE" class="Contract" insert="false" update="false" />
Insert into join table in many-to-many relationship
Problem #1: I have three tables; User, UserRole, and UserRoleRelationships (join table). The UserRole table contain all the user roles which I want to associate with the user. When I insert a new user I want to add a new user and add a new association in the join table. Now, when I'm running the query for inserting a new user: IWUser iwUser = new IWUser(); iwUser.setUsername("username"); iwUser.setFullName("fullName"); iwUser.setEmail("email"); iwUser.setPassword("password"); iwUser.setPrivatephone("55555"); iwUser.setWorkphone("777"); Set<IWUserRole> roleList = new HashSet<IWUserRole>(); IWUserRole iwUserRole = new IWUserRole(); iwUserRole.setRole("ROLE_USER"); roleList.add(iwUserRole); iwUser.setUserRole(roleList); iwUserManagementService.saveOrUpdate(iwUser); hibernate is running the following queries: Hibernate: insert into dbo.Users (Username, Password, Email, Workphone, Privatephone, FullName) values (?, ?, ?, ?, ?, ?) Hibernate: insert into dbo.UserRoles (Role) values (?) Hibernate: insert into UserRoleRelationships (UserId, RoleId) values (?, ?) My hibernate mapping looks like: IWUser.hbm.xml: <hibernate-mapping> <class name="domain.IWUser" schema="dbo" table="Users"> <id name="userId" type="int"> <column name="UserId"/> <generator class="native"/> </id> <property name="username" type="string"> <column name="Username" not-null="true"/> </property> <property name="password" type="string"> <column name="Password" not-null="true"/> </property> <property name="email" type="string"> <column name="Email" not-null="false"/> </property> <property name="workphone" type="string"> <column name="Workphone" not-null="false"/> </property> <property name="privatephone" type="string"> <column name="Privatephone" not-null="false"/> </property> <property name="fullName" type="string"> <column name="FullName" not-null="false"/> </property> <set cascade="all" inverse="false" name="userRole" table="UserRoleRelationships" lazy="true" > <key> <column name="UserId"/> </key> <many-to-many class="domain.IWUserRole" column="RoleId"/> </set> </class> </hibernate-mapping> IWUserRole.hbm.xml: <hibernate-mapping> <class name="domain.IWUserRole" schema="dbo" table="UserRoles"> <id name="roleId" type="int"> <column name="RoleId"/> <generator class="native"/> </id> <property name="role" type="string"> <column name="Role" not-null="true"/> </property> <set cascade="all" inverse="false" name="user" table="UserRoleRelationships" lazy="true"> <key> <column name="RoleId"/> </key> <many-to-many class="domain.IWUser" column="UserId"/> </set> </class> </hibernate-mapping> How can I get hibernate to save the new user with an existing user role in the join table? Problem #2: When I update the user, hibernate delete the relations in the join table. How can I avoid this?
How can I get hibernate to save the new user with an existing user role in the join table? Retrieve the user role entity and put that into the list instead of always creating a new one. I mean this part: IWUserRole iwUserRole = new IWUserRole(); iwUserRole.setRole("ROLE_USER"); Instead, you'd issue a query like select r from IWUserRole where r.role = 'ROLE_USER'
JPA mapping classes (openjpa)
Let's say I have a Question and QuestionHeader class. Question extends QuestionHeader. My mapping looks like this: <entity class="hr.leads.services.model.jpa.QuestionHeader"> <table name="question" /> <inheritance strategy="SINGLE_TABLE" /> <attributes> <basic name="description"> <column name="description" length="200" nullable="false" /> </basic> <basic name="text"> <column name="text" length="300" nullable="false" /> </basic> <many-to-one name="band" target-entity="hr.leads.services.model.jpa.Band" fetch="EAGER"> <join-column name="band_id" /> </many-to-one> </attributes> </entity> <entity class="hr.leads.services.model.jpa.Question"> <table name="question" /> <inheritance strategy="SINGLE_TABLE" /> <attributes> <basic name="visibilityQuestionId"> <column name="visibility_question_id" nullable="true" /> </basic> <basic name="visibilityQuestionOptionId"> <column name="visibility_question_option_id" nullable="true" /> </basic> <many-to-one name="questionType" target-entity="hr.leads.services.model.jpa.QuestionType" fetch="EAGER"> <join-column name="question_type_id" /> </many-to-one> <one-to-many name="options" target-entity="hr.leads.services.model.jpa.QuestionOption" fetch="EAGER" mapped-by="question"> <cascade> <cascade-all /> </cascade> </one-to-many> </attributes> </entity> The problem is, when I try to add the entity, here is the SQL that gets generated: INSERT INTO question (name, display_order, description, text, DTYPE, band_id, visibility_question_id, visibility_question_option_id, question_type_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [params=(String) q1, (int) 1, (String) d1, (String) t, (String) QUESTION, (long) 101, (long) 42, (long) 43, (long) 101]} It's putting DTYPE as a column name, and I don't want it to do that! How can I prevent it? I think this is the discriminator value, but I don't want that in my insert statement.
When using the SINGLE_TABLE strategy the discriminator column is needed to determine which subtype a entity belongs to. It's possible to rename and decide which value is stored on a per class basis. If you are not happy with this you two other strategies to choose from. Table per Class Join Please refer to the documentation for more information.