Intellij IDEA使用注解创建Hibernate项目中的OR映射类

       上回说到: Intellij IDEA下的第一个Hibernate项目 。我们需要创建 对象到关系的映射配置文件,如 entity.hbm.xml。(其中 entity 是我们将要创建的实体)
       下面讲的是  使用 注解 实现不用配置文件的对象到关系的映射过程。针对上一回讲到的在Intellij IDEA下创建Hibernate项目,这一次我们同样按照类似的步骤创建一个新的Module,这里我创建一个  Hibernate_01 Module。
       接下创建一个 Students 实体:
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第1张图片

Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第2张图片
       选择 hibernate.cfg.xml 右键,选择创建实体Entity(记得 要先按照上回讲到的,创建相应的 Hibernate 的配置文件 hibernate.cfg.xml



    
        root
        
        com.mysql.jdbc.Driver
        jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8
        org.hibernate.dialect.MySQLDialect

        true
        true
        create

        
        
    

):
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第3张图片

       选择在 entity 包下创建:
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第4张图片

       创建成功后,在Hibernate配置文件中会自动添加一行映射关系:
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第5张图片
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第6张图片

       Students.java
package entity;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

/**
 * Created by DreamBoy on 2016/5/16.
 */
@Entity
public class Students {
    private int sid;
    private String sname;
    private String gender;
    private Date birthday;
    private String address;

    public Students(int sid, String sname, String gender, Date birthday, String address) {
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.address = address;
    }

    @Id
    @Column(name = "sid")
    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    @Basic
    @Column(name = "sname")
    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "birthday")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Basic
    @Column(name = "address")
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Students students = (Students) o;

        if (sid != students.sid) return false;
        if (sname != null ? !sname.equals(students.sname) : students.sname != null) return false;
        if (gender != null ? !gender.equals(students.gender) : students.gender != null) return false;
        if (birthday != null ? !birthday.equals(students.birthday) : students.birthday != null) return false;
        if (address != null ? !address.equals(students.address) : students.address != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = sid;
        result = 31 * result + (sname != null ? sname.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        return result;
    }
}

       创建 Main.java,内容如下:
import entity.Students;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.util.Date;

/**
 * Created by DreamBoy on 2016/5/15.
 */
public class Main {
    /*private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        try {
            System.out.println("querying all the managed entities...");
            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
            for (Object key : metadataMap.keySet()) {
                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
                final String entityName = classMetadata.getEntityName();
                final Query query = session.createQuery("from " + entityName);
                System.out.println("executing: " + query.getQueryString());
                for (Object o : query.list()) {
                    System.out.println("  " + o);
                }
            }
        } finally {
            session.close();
        }
    }*/

    public static void main(String[] args) {
        //创建配置对象,获取hibernate.cfg.xml配置文件的信息
        Configuration config = new Configuration().configure();
        //创建服务注册对象,创建和销毁都相当耗费资源,通常一个系统内一个数据库只创建一个
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工厂对象,类似于JDBC的Connection
        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        Session session = sessionFactory.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        //生成学生对象
        Students s = new Students(1, "张三丰", "男", new Date(), "武当山");
        session.save(s); //保存对象进入数据库

        transaction.commit(); //提交事务
        session.close(); //关闭会话
        sessionFactory.close(); //关闭会话工厂
    }
}

       运行Main.java,会看如下运行结果:
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第7张图片
Intellij IDEA使用注解创建Hibernate项目中的OR映射类_第8张图片
       在 名为 hibernate 的数据库下 创建了 Students 表,并插入了一条数据。


你可能感兴趣的:(JavaEE)