· 8 years ago · Nov 28, 2017, 04:52 PM
1CREATE TABLE IF NOT EXISTS engines (
2 id SERIAL PRIMARY KEY,
3 model VARCHAR(25) UNIQUE NOT NULL,
4 power INTEGER NOT NULL
5);
6
7CREATE TABLE IF NOT EXISTS cars (
8 id SERIAL PRIMARY KEY,
9 mark VARCHAR(25) NOT NULL,
10 model VARCHAR(25) NOT NULL,
11 engine_id INTEGER NOT NULL,
12 FOREIGN KEY (engine_id) REFERENCES engines (id)
13);
14
15ERROR: duplicate key value violates unique constraint "engines_model_key"
16 Detail: Key (model)=(test) already exists.
17
18<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
19
20 <class name="ru.javavision.model.Car" table="cars">
21 <id name="id" column="id">
22 <generator class="identity"/>
23 </id>
24 <property name="mark" column="mark"/>
25 <property name="model" column="model"/>
26
27 <!--ПрикреплÑем ÑущьноÑть двигателÑ-->
28 <many-to-one name="engine" column="engine_id"
29 class="ru.javavision.model.Engine"
30 cascade="save-update" not-null="true"/>
31 </class>
32</hibernate-mapping>
33
34<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
35
36 <class name="ru.javavision.model.Engine" table="engines">
37 <id name = "id" type = "int" column = "id">
38 <generator class="identity"/>
39 </id>
40 <property name="model" column="model"/>
41 <property name="power" column="power"/>
42 </class>
43</hibernate-mapping>
44
45private final SessionFactory factory = ...;
46
47public void create(@NotNull final Car car) {
48
49 try (final Session session = factory.openSession()) {
50
51 session.beginTransaction();
52
53 session.save(car);
54
55 session.getTransaction().commit();
56 }
57}