Hibernate(二)——基本映射

来源:互联网 发布:python context 编辑:程序博客网 时间:2024/04/30 08:01

Hibernate不仅负责从Java类到数据库表的映射,还提供了面向对象数据查询检索机制,从而极大地缩短了手动处理SQL和JDBC上的开发时间。


也就是说,采用Hibernate框架进行开发,我们无需关心数据库中有哪些表。取而代之的是,通过配置文件的基本映射,我们能够完全采用面向对象的方式,完成持久层的持久化数据处理。


首先,从宏观上了解Hibernate的基本映射。




下面做一个Hibernate做一个映射Demo:

User实体:

package com.lzq.hibernate;import java.util.Date;public class User {private String id;private String name;private String password;private Date createTime;private Date expireTime;……getter/setter方法……}


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><class name="com.lzq.hibernate.User" table="t_user">                <!-- 一种主键生成策略:uuid-->                <id name="id"><generator class="uuid" /></id>                <!-- 映射name属性-->                <property name="name" /><property name="password" /><property name="createTime" /><property name="expireTime" /></class></hibernate-mapping>


在hibernate.cfg.xml文件里,建立Hibernate与User的联系。

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_test</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- hibernate与实体User建立联系 --><mapping resource="com/lzq/hibernate/User.hbm.xml"/></session-factory></hibernate-configuration>


这样,就映射了User实体,以后,我们就可以通过面向对象的方式操作User实体,进而间接对数据库进行操作。

原创粉丝点击