This article describes the hibernate's annotation version of the Hello World implementation method. Share to everyone for your reference, specific as follows:
Packages to introduce: Hibernate-commons-annotations-4.0.4.final.jar
Because I am using: hibernate-release-4.3.5.final, in the required directory already have.
Bean:
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.Id;
Import javax.persistence.Table;
@Entity
@Table (name= "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;
}
@Column (name= "name") public
String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
@Column (name= "title") Public
String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
}
The corresponding Hibernate.cfg.xml file:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">
Test class:
Import org.hibernate.Session;
Import org.hibernate.SessionFactory;
Import org.hibernate.cfg.AnnotationConfiguration;
Import org.hibernate.cfg.Configuration;
Import com.huxing.hibernate.model.Student;
Import Com.huxing.hibernate.model.Teacher;
public class Studenttest {public
static void Main (string[] args) {
Student a = new Student ();
A.setid (123);
A.setage (a);
A.setname ("Hello hibernate!");
Teacher tea = new Teacher ();
Tea.setid (4);
Tea.setname ("MySQL");
Tea.settitle ("High");
Configuration cfg = new annotationconfiguration ();
Sessionfactory CF = Cfg.configure (). Buildsessionfactory ();
Session session = Cf.opensession ();
Session.begintransaction ();
Session.save (tea);
Session.gettransaction (). commit ();
Session.close ();
Cf.close ();
}
Note: The code omits the package path.
Other aspects:
1. Annotations can be added to a property or added to a GET method.
2. Annotation mapping and XML configuration of XML are different! One is resource, one is class.
I hope this article will help you to hibernate framework program design.