美文网首页
Hibernate入门1

Hibernate入门1

作者: 阿敏MIN | 来源:发表于2018-11-22 21:55 被阅读9次

    1.是什么?

    2.代码实现

    • 需求1:使用hibernate实现(连接数据库+自动建表)
      第一步:建bean(User.java)
    public class User {
        private int uid;
        private String uname;
        private String upw;
        //省略Getter&Setter
    }
    

    第二步:建bean的映射文件(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.yy1811.hibernate.bean.User" 
                table="user">
                <id
                name="uid"
                column="uid"
                length="36">
                <generator
                    class="assigned" />
                </id>
                    <property
                        name="uname"
                        column="uname"
                        update="true"
                        insert="true"
                        length="200"
                        not-null="true" />
                    <property
                        name="upw"
                        column="upw"
                        update="true"
                        insert="true"
                        length="200"
                        not-null="true" />
            </class>
    </hibernate-mapping>
    

    第三步:建hibernate的配置文件(hibernate.cfg.xml)

    <?xml version="1.0" encoding="utf-8"?>
    <!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.url">
                jdbc:mysql://localhost:3306/test
            </property>
            <property name="hibernate.connection.driver_class">
                com.mysql.jdbc.Driver
            </property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>  
            <!-- 是否启动表结构自动生成 -->
            <property name="hbm2ddl.auto">update</property>
            <!-- 是否在控制台显示SQL语句 -->
            <property name="show_sql">true</property>
            <!-- 下面这一句是重点!!!特别是路径,千万别搞错 -->
            <mapping resource="com/yy1811/hibernate/bean/User.hbm.xml" />
        </session-factory>
    </hibernate-configuration>
    

    相关文章

      网友评论

          本文标题:Hibernate入门1

          本文链接:https://www.haomeiwen.com/subject/rpmrqqtx.html