Results 1 to 1 of 1
- 09-27-2012, 04:01 AM #1
Member
- Join Date
- Jun 2012
- Posts
- 2
- Rep Power
- 0
how to persist foreign key only if not exist?
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.
Java 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);
Java Code:em.persist(report); em.flush();
Java 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 );
Java 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; // ...
Similar Threads
-
Can someone please help me persist data to a database
By alexandra12 in forum New To JavaReplies: 2Last Post: 08-24-2012, 04:24 PM -
Persist data
By eclectica in forum SpringReplies: 6Last Post: 06-19-2012, 01:01 PM -
How to persist multidimensional Java arrays using JPA
By T_O_B_E_E in forum JDBCReplies: 0Last Post: 02-14-2011, 04:24 PM -
Exist or not exist file problem
By Ballister in forum New To JavaReplies: 6Last Post: 12-26-2010, 08:29 PM
Bookmarks