Getting started with Hibernate (2)

Source: Internet
Author: User

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();}}

  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.