(13)Hibernate組件映射

來源:互聯網
上載者:User

標籤:hibernate


不相信自己的人 連努力的價值都沒有。


類組合關係的映射,也叫做組件映射!

注意:組件類和被包含的組件類,共同映射到一張表!

需求: 汽車與車輪

產生的表:主鍵、汽車名稱、輪胎大小、輪胎數量


Wheel.java

package com.rk.hibernate.m_component;public class Wheel{private int count;private int size;public int getCount(){return count;}public void setCount(int count){this.count = count;}public int getSize(){return size;}public void setSize(int size){this.size = size;}}

Car.java

package com.rk.hibernate.m_component;public class Car{private int id;private String name;private Wheel wheel;public int getId(){return id;}public void setId(int id){this.id = id;}public String getName(){return name;}public void setName(String name){this.name = name;}public Wheel getWheel(){return wheel;}public void setWheel(Wheel wheel){this.wheel = wheel;}}

Car.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.rk.hibernate.m_component" auto-import="true"><class name="Car" table="T_Cars"><id name="id" column="carId"><generator class="native"></generator></id><property name="name" column="carName"></property><!-- 組件映射 --><component name="wheel"><property name="size" column="wheelSize"></property><property name="count" column="wheelCount"></property></component></class></hibernate-mapping>

App.java

package com.rk.hibernate.m_component;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.junit.Test;public class App{private static SessionFactory sf;static{sf = new Configuration().configure().addClass(Car.class).buildSessionFactory();}@Testpublic void testSave(){Session session = sf.openSession();session.beginTransaction();// 輪子Wheel wheel = new Wheel();wheel.setSize(80);wheel.setCount(4);// 汽車Car car = new Car();car.setName("BMW");car.setWheel(wheel);// 儲存session.save(car);session.getTransaction().commit();session.close();}}

產生的資料表

650) this.width=650;" src="http://s1.51cto.com/wyfs02/M02/84/2E/wKiom1eHi-rjXXWaAAAJdM6oM4A951.png" title="T_Cars.PNG" alt="wKiom1eHi-rjXXWaAAAJdM6oM4A951.png" />


(13)Hibernate組件映射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.