Hibernate HelloWorld Annotation

Annontation版HelloWorld
大概步骤:
1、建表
2、建立实体类,同时添加注释
3、hibernate配置文件,注意添加实体类映射配置
4、测试


具体步骤及代码如下:
1、建表
create table t_teacher(
id int primary key,
name varchar(20),
title varchar(20));
2、建立实体类
package helloworld_annotation;

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

@Entity
@Table(name="t_teacher")
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;
	}

}



3、hibernate配置文件
<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="connection.driver_class">
		oracle.jdbc.driver.OracleDriver
	</property>
	<property name="connection.url">
		jdbc:oracle:thin:@localhost:1521:orcl
	</property>
	<property name="connection.username">tysp</property>
	<property name="connection.password">12345678</property>
	<property name="connection.driver_class">
		oracle.jdbc.driver.OracleDriver
	</property>
	<property name="dialect">
		org.hibernate.dialect.OracleDialect
	</property>
	
	<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">create</property> -->

     <!--  注意不同 xml是resource、斜杠分割 annotation是class、点分割  --
     <mapping class="helloworld_annotation.Teacher"/>

</session-factory>

</hibernate-configuration>


4、测试

package helloworld_annotation;

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

public class TestTeacher {
	
	public static void main(String[] args){
		
		Teacher t = new Teacher();
		t.setId(1);
		t.setName("t1");
		t.setTitle("高级");
		
		Configuration conf = new AnnotationConfiguration();
		SessionFactory sf = conf.configure().buildSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		tx.begin();
		session.save(t);
		tx.commit();
		session.close();
	}

}


你可能感兴趣的:(annotation)