组件映射:Group类的描写
User类是一个组件
User类:
配置文件Group.hbm.xml:
配置文件User.hbm.xml:
测试代码:
User类是一个组件
package com.anryn;
public class Group {
private int id ;
private String address ;
private User user ;
public Group() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User类:
package com.anryn;
import java.util.Date;
public class User {
private int id ;
private String useName ;
private Date date ;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUseName() {
return useName;
}
public void setUseName(String useName) {
this.useName = useName;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
配置文件Group.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.anryn">
<class name="Group" table="_Group">
<!--hibernate为我们生成主键id-->
<id name="id">
<generator class="native"/>
</id>
<property name="address"/>
<component name="user" class="User">
<property name="id" column="User_Id"/>
<property name="useName"/>
<property name="date"/>
</component>
</class>
</hibernate-mapping>
配置文件User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.anryn">
<class name="User" table="User">
<id name="id">
<generator class="native"/>
</id>
<property name="useName"/>
<property name="date"/>
</class>
</hibernate-mapping>
测试代码:
package com.anryn;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class UserTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User() ;
user.setUseName("anryn") ;
user.setDate(new Date()) ;
Group group = new Group() ;
group.setAddress("武汉市");
group.setUser(user) ;
//getSession
SessionFactory sf = new Configuration().configure().buildSessionFactory() ;
Session session = sf.getCurrentSession() ;
session.beginTransaction() ;
session.save(user) ;
session.save(group) ;
session.getTransaction().commit() ;
sf.close() ;
}
}