二、一对多(单向)

Bean:

public class Car implements Serializable{

    private int id ;
    
    private String name ;
    
    private User user ;
        
        ....
}
public class User implements Serializable {
    
    private int id ;
    
    private String name ;
    
    private Set<Car> cars ;
        ....
}

xml配置:

Car.hbm.xml:
<class name = "Car">
        <!-- id是来配置主键 
             name是类中的哪个属性和主键映射
             generator:表示主键的生成策略
        -->
        <id name = "id">
            <generator class="native" />
        </id>
        <!-- property是用来把类中的属性和表的字段做一一对应 -->
        <property name="name" />
        
    </class>
User.hbm.xml:
<class name = "User">
        <!-- id是来配置主键 
             name是类中的哪个属性和主键映射
             generator:表示主键的生成策略
        -->
        <id name = "id">
            <generator class="native" />
        </id>
        <!-- property是用来把类中的属性和表的字段做一一对应 -->
        <property name="name" />
        
        <set name="cars" cascade="all">
            <key column="uid" />
            <one-to-many class="Car"/>
        </set>
    </class>

annotation配置:

@Entity
public class Car implements Serializable{

    @Id @GeneratedValue
    public int getId() {
        return id;
    }

} 

@Entity
public class User implements Serializable {
        @Id @GeneratedValue
    public int getId() {
        return id;
    }

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="uid")
    public Set<Car> getCars() {
        return cars;
    }
}