Getting started with Hibernate (2)
I. annotation for Hibernate
You can use annotations to create Hibernate programs. The advantage of annotations is that you do not need to create a ing file to directly create object associations.
To use hibernate annotations, you must import the JAR packages related to annotations.
1. Download the JAR package
It mainly includes the basic hibernate JAR package, the database connection JAR package, and the annotation JAR package.
2. Create a project and import the JAR package
3. Create a New hibernate. cfg. xml configuration file.
Create a new hibernate. cfg. xml configuration file and configure global properties such as database links.
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
4. Create a persistence class
package com;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="user")public class User {@Idprivate int id;@Column(name="name")private String name;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;}}
5. Add configuration in hibernate. cfg. xml
<mapping class="com.User"/>
6. Create a test class
package com;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.AnnotationConfiguration;public class Test {public static void main(String[] args) {SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory();Session session = factory.openSession();Transaction t = session.beginTransaction();t.begin();User user = new User();user.setId(2);user.setName("Tom");session.save(user);t.commit();session.close();}}