用户工具


实现数据库表和javabean类的映射关系

hibernate核心配置文件(hibernate.cfg.xml)

<hibernate-configuration>
    <session-factory>
        <!-- 数据源定义 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456 </property>
        
        <!--class 数据库表的描述文件”-->
        <mapping resource="org/mxg/Class.hbm.xml"></mapping>
        <!--user_info 数据库表的描述文件”-->
        <mapping resource="org/mxg/UserInfo.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

数据库表描述文件(数据库表 到 javabean类的映射)

<!--描述了数据库class表 到 javabean中字段的对应关系-->
<hibernate-mapping>
    <class name="entity.Class" table="t_class">
        <id  name="id" type="integer">
            <column name="id"></column>
            <generator class="native"></generator>
        </id>
        <property name="name">
            <column name="name"></column>
        </property>
        <property name="pwd">
            <column name="pwd"></column>
        </property>
        <property name="age">
            <column name="age"></column>
        </property>
    </class>
</hibernate-mapping>

<!--描述了数据库user_info表 到 javabean中字段的对应关系-->
<hibernate-mapping>
    <class name="entity.UserInfo" table="t_user_info">
        <id  name="id" type="integer">
            <column name="id"></column>
            <generator class="native"></generator>
        </id>
        <property name="name">
            <column name="name"></column>
        </property>
        <property name="pwd">
            <column name="pwd"></column>
        </property>
        <property name="age">
            <column name="age"></column>
        </property>
    </class>
</hibernate-mapping>

javabean类(数据库表在程序中展现的形式)

public class UserInfo{

    private int id;

    private String name;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

使用方式

       public static void main(String[] args) {
            Session session = SessionFactoryUtil.getInstance().getCurrentSession();
            Transaction tx = session.beginTransaction();
            User user = new User();//瞬态
            user.setId("aaa");
            session.save(user);//持久态
        }