VIRGIN FOREST OF JAVA
不要埋头苦干,要学习,学习,再学习。。。。。
powered by R.Zeus
for example


CREATE TABLE user (
    id INT(11) NOT NULL auto_increment PRIMARY KEY,
    name VARCHAR(100) NOT NULL default ''
);

CREATE TABLE room (
    id INT(11) NOT NULL auto_increment PRIMARY KEY,
    address VARCHAR(100) NOT NULL default ''
);


User.hbm.xml

  • 										<?xml version="1.0" encoding="utf-8"?> 
    <!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>

    <class name="onlyfun.caterpillar.User" table="user">
    <id name="id" column="id" type="java.lang.Integer">
    <generator class="native"/>
    </id>

    <property name="name" column="name" type="java.lang.String"/>

    <one-to-one name="room"
    class="onlyfun.caterpillar.Room"
    cascade="all"/>
    </class>

    </hibernate-mapping>

    • Room.hbm.xml
    										<?xml version="1.0" encoding="utf-8"?> 
    <!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>

    <class name="onlyfun.caterpillar.Room" table="room">
    <id name="id" column="id">
    <generator class="foreign">
    <param name="property">user</param>
    </generator>
    </id>

    <property name="address"
    column="address"
    type="java.lang.String"/>

    <one-to-one name="user"
    class="onlyfun.caterpillar.User"
    constrained="true"/>
    </class>

    </hibernate-mapping>
				
						java:
						










User user1 = new User();

user1.setName("bush");
Room room1 = new Room();
room1.setAddress("NTU-M8-419");
       
user1.setRoom(room1);
room1.setUser(user1);
       
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
 
session.save(user1);

       
tx.commit();
session.close();






the above is run right,but if the following :


User user1 = new User();
user1.setName("bush");

Room room1 = new Room();
room1.setAddress("NTU-M8-419");
       
user1.setRoom(room1);
room1.setUser(user1);



User user2 = new User();
user2.setName("bush");


//the new column point to the same room1 and no errors

user2.setRoom(room1);
       
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
 
session.save(user1);
//save



  session.save(user2);
     

tx.commit();
session.close();



is "one-to-one" in hibernate just for creating  a foreign key for another table?
did it make any restriction between the two tables.
posted on 2006-08-28 13:45 R.Zeus 阅读(217) 评论(0)  编辑  收藏 所属分类: Hibernate

只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问