hibernate-annotation 方式

hibernate官网:http://www.hibernate.org/

annotation

 [ænə'teɪʃ(ə)n]    注释

 

 

jar包

在hibernate-distribution-3.5.6-Final里,因为hibernate3的包下有hibernate-annotations.jarhibernate-commons-annotations.jar这两个jar包已经和进去了,所以只需要导入

ejb3-persistence.jar和hibernate-jpa-2.0-api-1.0.1.Final.jar

这两个包即可实现annotation方式的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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/mydb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</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 class="pojo.Customer"/>
    </session-factory>

</hibernate-configuration>

 

 

 [Customer.java]

package pojo;

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

@Entity
public class Customer {
 private int id;
 private String name;
 private String password;
 @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 getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
}

[test]

 package mytest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import pojo.Customer;

 

public class test {
 public static void main(String[] args) {
  Customer t=new Customer();
  t.setId(5);
  t.setName("t2");
  t.setPassword("middle");

  SessionFactory sessionFactory = new AnnotationConfiguration()
    .configure().buildSessionFactory();
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  session.save(t);
  session.getTransaction().commit();
 }

}

posted on 2015-01-21 13:45  ziyi_ang  阅读(72)  评论(0编辑  收藏  举报

导航