users@glassfish.java.net

how to persist foreign key only if entry doesn't exist?

From: <forums_at_java.net>
Date: Wed, 26 Sep 2012 19:10:22 -0500 (CDT)

The Car table is a list of cars, all unique. The Engine table is a list of
engines, all unique. The Report table has a reference to the Car table as
shown below. There can be many reports, but I don't want to duplicate
anything in the Car or Engine tables. My problem is I want to insert a
Report, but only insert a car into the Car table if its not already in the
Car table. Currently, all this works with the exception that Cars are being
duplicated into the Car table when I add a report. Any help much appreciated.
[code] ireport = (IReportBean) (new
InitialContext()).lookup("java:comp/env/ejb/ReportBean"); Car car = new
Car(c); Report report = new Report(r); report.addCar(car);
ireport.addReport(report); [/code] And my EntityManager basically does ...
[code] em.persist(report); em.flush(); [/code] My table structure ... [code]
CREATE SEQUENCE report_seq START 1000; CREATE TABLE Report ( id INTEGER
DEFAULT NEXTVAL('report_seq') PRIMARY KEY, car_id INTEGER REFERENCES Car
(id), condition VARCHAR(32) NOT NULL ); CREATE SEQUENCE car_seq START 1000;
CREATE TABLE Car ( id INTEGER DEFAULT NEXTVAL('car_seq') PRIMARY KEY,
engine_id INTEGER REFERENCES Engine (id), mfg VARCHAR(32) NOT NULL ); CREATE
SEQUENCE engine_seq START 1000; CREATE TABLE Engine ( id INTEGER DEFAULT
NEXTVAL('engine_seq') PRIMARY KEY, year VARCHAR(32) NOT NULL, description
VARCHAR(128) DEFAULT NULL ); [/code] Annotations used in my Report entity.
[code] @SequenceGenerator(name="reportIdGen", initialValue=1000,
allocationSize=50, sequenceName="report_seq") public class Report implements
Serializable { @Id @Column(name="id")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="reportIdGen")
private Integer id; @ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="car_id") private Car carId; @Column(name="condition")
private String condition; // ... [/code]

--
[Message sent by forum member 'rrlangly']
View Post: http://forums.java.net/node/890713