Hibernate--(一)

东方咖啡屋 2020-01-06

项目结构:

Hibernate--(一)

表:

 Hibernate--(一)

1.实体类:

public class Product {
    int id;
    String name;
    float price;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
}

2.Product.hbm.xml

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
        <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.how2j.pojo">
    <class name="Product" table="product_">
        <id name="id" column="id">
            <generator class="native"></generator>
        </id>
        <property name="name" />
        <property name="price" />
    </class>
</hibernate-mapping>

3.hibernate.cfg.xml

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>


        <mapping resource="com/h/pojo/Product.hbm.xml" />
    </session-factory>
</hibernate-configuration>

4.Test.java

public class Test {

    public static void main(String[] args) {
        /*
        hibernate的基本步骤是:
        1. 获取SessionFactory
        2. 通过SessionFactory 获取一个Session
        3. 在Session基础上开启一个事务
        4. 通过调用Session的save方法把对象保存到数据库
        5. 提交事务
        6. 关闭Session
        7. 关闭SessionFactory
         */
        SessionFactory sf = new Configuration().configure().buildSessionFactory();

        Session s = sf.openSession();
        s.beginTransaction();

        Product p = new Product();
        p.setName("iphone7");
        p.setPrice(7000);
        s.save(p);

        s.getTransaction().commit();
        s.close();
        sf.close();
    }

5.成功

Hibernate--(一)

 Hibernate--(一)

相关推荐

LetonLIU / 0评论 2020-05-29