最后建立数据库表对应的实体类Cuser.java:
[java]
package collect.component;
public class Cuser {
private Integer id;
private Integer age;
private Name name;
private Contact contact;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
建立映射文件Cuser.hbm.xml:
[html]
注解:映射文件使用component元素将Name类、Contact类同数据库表c_user联系起来。
将该映射文件加入到Hibernate的配置文件中,建立一个测试类Test.java:
[java]
package collect.component;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
// Configuration管理Hibernate配置
Configuration config = new Configuration()。configure();
// 根据Configuration建立 SessionFactory
// SessionFactory用来建立Session
SessionFactory sessionFactory = config.buildSessionFactory();
// 创建实例
Name name=new Name();
name.setFirstname("闫");
name.setLastname("术卓");
Contact contact = new Contact();
contact.setAddress("北京");
contact.setTel("42689334");
contact.setZipcodes("100085");
Cuser user= new Cuser();
user.setAge(33);
user.setName(name);
user.setContact(contact);
// 定义主键变量
Integer pid;
// 添加数据
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// 创建主键变量
pid = (Integer) session.save(user);
tx.commit();
} catch (RuntimeException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
// 关闭sessionFactory
sessionFactory.close();
}
}
运行结果:
控制台:
20:47:57,366 DEBUG SQL:346 - insert intossh.c_user (age, firstname, lastname, address, zipcode, tel) values (?, ?, ?,?, ?, ?)
更多关注: