数据库表中有几列的数据都是类似的,可以使用一个独立的实体类来表示,这个就叫做组件映射,即有个实体类或者多个实体类对应一张数据库表。
User类
package test;
public class User {
private int id;
private String name;
private Address address;
}
Address类
public class Address {
private String addr1 ;
private String addr2 ;
private String addr3 ;
}
User类的User_hbm.xml
hibernate.cfg.xml(Address不需要hbm.xml)
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory><!-- serverTimezone=GMT%2B8 -->
<!-- 连接数据库及hibernate的方言配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testconn?serverTimezone=GMT%2B8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- hibernate的其他配置 -->
<property name="hibernate.show_sql">true</property><!--在控制台中打印sql语句 -->
<property name="hibernate.format_sql">true</property><!-- 打印前格式化sql一句 -->
<!-- ddl策略 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 设置是否自动提交事务 -->
<property name="hibernate.connection.autoconmmit">false</property>
<mapping resource="test/User_hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil工厂类
public class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory factory = null;
private static Session session = null ;
static {
init();
}
public static void init() {
cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}
public static Session getSession() {
if (factory != null){
return session = factory.openSession();
}
init();
return session = factory.openSession();
}
public static void closeSession() {
if(session!=null && session.isOpen())
session.close();
}
}
通过Jubit5测试:
public class Test {
/**
* 根据*.hbm.xml文件对应的生成数据库表
*/
@org.junit.Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
}
/**
* @throws HibernateException
* @throws SerialException
* @throws SQLException
* @throws IOException
*/
@org.junit.Test
public void testSave() throws HibernateException, SerialException,
SQLException, IOException {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSession();
tx = session.beginTransaction();
User user = new User();
user.setName("Waylon");
Address address = new Address();
address.setAddr1("北京朝阳");
address.setAddr2("东城区");
address.setAddr3("西城区");
user.setAddress(address) ;
session.save(user);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
throw e;
} finally {
HibernateUtil.closeSession();
}
}
}
生成的SQL语句
查看数据库的数据