· 8 years ago · Nov 28, 2017, 07:12 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
15<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
16
17 <class name="ru.javavision.model.Car" table="cars">
18 <id name="id" column="id">
19 <generator class="identity"/>
20 </id>
21 <property name="mark" column="mark"/>
22 <property name="model" column="model"/>
23
24 <!--ПрикреплÑем ÑущьноÑть двигателÑ-->
25 <many-to-one name="engine" column="engine_id"
26 class="ru.javavision.model.Engine"
27 cascade="save-update" not-null="true"/>
28 </class>
29</hibernate-mapping>
30
31<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
32
33 <class name="ru.javavision.model.Engine" table="engines">
34 <id name = "id" type = "int" column = "id">
35 <generator class="identity"/>
36 </id>
37 <property name="model" column="model"/>
38 <property name="power" column="power"/>
39 </class>
40</hibernate-mapping>
41
42private final SessionFactory factory = ...;
43
44public void create(@NotNull final Car car) {
45
46 try (final Session session = factory.openSession()) {
47
48 session.beginTransaction();
49
50 session.save(car);
51
52 session.getTransaction().commit();
53 }
54}