Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Hibernate from updating existing records

I am trying to get hibernate to write new objects each time I do a save as opposed to updating the existing records.

public class Risk {
    private long riskID;
    private Vehicle vehicle;
}

public class Vehicle {  
    private long vehicleID;
    private long riskID;
    private String regNumber;
    private String abiCode;
    private String make;
    private String model;
}

So if a write the risk to the DB. Then I change vehicle on the web and try to save the risk to the DB a second time. I would like to to have two risks in the risk table and two vehicles in the vehicle table.

Currently I am using the hibernate session Save(Object o). This is always creating a new risk in the DB but never creating a new vehicle. It is just updating the original one.

Here is my mapping file:

<?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 lazy="false" name="uk.co.test.Risk" schema="quote_engine" table="GV_RISK" >
    <id column="riskID" name="riskID" type="long">
        <generator class="identity"/>
    </id>

    <many-to-one name="vehicle" class="uk.co.test.Vehicle" column="vehicleID" not-null="true" cascade="all" unique="true" />

</class>

<?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="uk.co.test.Vehicle" schema="quote_engine" table="GV_VEHICLE">

    <id name="vehicleID" type="long" column="vehicleID">
        <generator class="identity" />
    </id>

    <property name="regNumber" type="string" column="regNumber" />
    <property name="abiCode" type="string" column="abiCode" />
    <property name="make" type="string" column="make" />
    <property name="model" type="string" column="model" />


</class>

like image 770
shawsy Avatar asked Nov 28 '22 22:11

shawsy


1 Answers

I really doubt that it's possible to make Hibernate do this auto-magically. You're wanting to override one of the most basic behaviors of ORMs. Their whole bag is they keep track of your objects in some Session in order to persist those updates to the database without you having to sort through those updates yourself.

If you don't want records updated, make your setters private and annotate your fields so that you get field access. In xml, set the default-access="field" property on your <hibernate-mapping> tag.

Then you need to create a new object before adding it to your session. Have a service with a method that looks something like this:

public void saveVehicle(Vehicle vehicle) {
  Vehicle vehicleNew = vehicle.copy();
  // Risk would be copied via risk.copy() in vehicle.copy()

  vehicleDao.save(vehicleNew)
}
like image 71
Tim Pote Avatar answered Dec 10 '22 03:12

Tim Pote