- hibernate 一个对象对应两张表
- OR映射的设置
- 一个对象对应一张表
- User <-----> Person1
- 一个对象对应两张表
- User <-----> Person1 , Phone1
- Person1 :ID ,Name
- Phone1 :PersonID PK,PhoneCode PK
- 自然主键或物理主键
- 在User对象中需要添加一个映射Phone1表的属性(集合属性)
- 集合属性有三种:List,Set,Map
- List 有元素下标
- Map 有键值
- Set 没有重复值即可
- model.xml
- <hibernate-mapping>
- <class name="my.User" table="Person1" schema="dbo" catalog="Demo">
- <id name="uid" type="int">
- <column name="ID" />
- <generator class="assigned"></generator>
- </id>
- <property name="uname" type="string">
- <column name="Name" length="50" not-null="true" />
- </property>
- <set name="phoneSet" table="Phone1" >
- <key column="PersonID" />
- <element column="PhoneCode" type="string" />
- </set>
- </class>
- </hibernate-mapping>
- User.java
- public class User {
- private int uid;
- private String uname;
- private Set phoneSet=new HashSet();
- public User() {}
- public User(int uid, String uname) {
- this.uid = uid;
- this.uname = uname;
- }
- public int getUid() {
- return this.uid;
- }
- public void setUid(int uid) {
- this.uid = uid;
- }
- public String getUname() {
- return this.uname;
- }
- public void setUname(String uname) {
- this.uname = uname;
- }
- public Set getPhoneSet() {
- return phoneSet;
- }
- public void setPhoneSet(Set phoneSet) {
- this.phoneSet = phoneSet;
- }
- }
- UserOp.java
- public class UserOp {
- private Session se=null;
- public UserOp(){
- //1:读配置文件
- Configuration config=new Configuration().configure();
- //2:建会话工厂
- SessionFactory sf=config.buildSessionFactory();
- //3:获取和数据库的会话(连接)
- se= sf.openSession();
- }
- public void QueryAll(){
- List list=null;
- //1:创建执行查询用的对象(Query)
- Query query=se.createQuery("from User");
- //2:获取返回的结果集(List)
- list= query.list();
- //3:遍历集合
- Iterator iter=list.iterator();
- while(iter.hasNext()){
- User temp=(User)iter.next();
- System.out.println(temp.getUid()+":"+temp.getUname());
- }
- }
- public void AddUser(User u){
- se.save(u);
- se.beginTransaction().commit();
- }
- public void UpdUser(User u){
- se.update(u);
- se.beginTransaction().commit();
- }
- public void DelUser(User u){
- se.delete(u);
- se.beginTransaction().commit();
- }
- }
- Test.java
- public class Test {
- public static void main(String[] args) {
- //1:生成操作User对象实例
- UserOp op=new UserOp();
- //2:执行对数据更改
- //2.1
- User u=new User(4,"小虫");
- Set phoneSet=new HashSet();
- phoneSet.add("022-21331111");
- phoneSet.add("13511112222");
- u.setPhoneSet(phoneSet);
- //2.2
- op.AddUser(u);
- //3:查询结果
- op.QueryAll();
- }
- }
下面是List集合
<class name="my.User" table="Person1" >
<id name="uid" column="ID" type="int" >
<generator class="assigned" />
</id>
<property name="uname" column="Name" type="string" length="50" />
<list name="phones" table="Phone1">
<key column="PID" /> //联合主键PID,ORD 其中ORD是索引列如果使用
list集合就必须手动添加该列
<index column="ORD" />
<element column="Code" type="string" length="50" />
</list>
</class>