【Hibernate3.3复习知识点二】 - 配置hibernate环境(annotations)

 

配置文件hibernate.cfg.xml中引入:<mapping class="com.bjsxt.hibernate.Teacher"/>

<hibernate-configuration>



    <session-factory>



        <!-- Database connection settings -->

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>

        <property name="connection.username">root</property>

        <property name="connection.password">bjsxt</property>



        <!-- JDBC connection pool (use the built-in) -->

        <property name="connection.pool_size">1</property>



        <!-- SQL dialect -->

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>



        <!-- Enable Hibernate's automatic session context management -->

        <property name="current_session_context_class">thread</property>



        <!-- Disable the second-level cache  -->

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>



        <!-- Echo all executed SQL to stdout -->

        <property name="show_sql">true</property>



        <!-- Drop and re-create the database schema on startup -->

        <property name="hbm2ddl.auto">update</property>



        <mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>

        <mapping class="com.bjsxt.hibernate.Teacher"/>

    </session-factory>



</hibernate-configuration>
View Code

 

实体类:

package com.bjsxt.hibernate;



import javax.persistence.Entity;

import javax.persistence.Id;



@Entity

public class Teacher {

    private int id;

    private String name;

    private String title;

    

    @Id

    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 String getTitle() {

        return title;

    }

    public void setTitle(String title) {

        this.title = title;

    }

}
View Code

注解所在包:

import javax.persistence.Entity;
import javax.persistence.Id;

类与主键:@Entity  @ Id

 

测试类:

public class TeacherTest {

    public static void main(String[] args) {

        Teacher t = new Teacher();

        t.setId(1);

        t.setName("t1");

        t.setTitle("middle");

        

        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

        Session session = sessionFactory.getCurrentSession();

        session.beginTransaction();

        session.save(t);

        session.getTransaction().commit();

    }

}
View Code

注解形式新建sessionFactory 时用new AnnotationConfiguration()。

 

你可能感兴趣的:(Annotations)