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

本文介绍如何在IntelliJ IDEA环境中利用Hibernate框架通过注解方式完成对象关系映射。主要内容包括创建实体类Students并使用注解定义其属性与数据库表字段之间的映射关系,以及创建Main类来演示数据的保存过程。
       上回说到: Intellij IDEA下的第一个Hibernate项目 。我们需要创建 对象到关系的映射配置文件,如 entity.hbm.xml。(其中 entity 是我们将要创建的实体)
       下面讲的是  使用 注解 实现不用配置文件的对象到关系的映射过程。针对上一回讲到的在Intellij IDEA下创建Hibernate项目,这一次我们同样按照类似的步骤创建一个新的Module,这里我创建一个  Hibernate_01 Module。
       接下创建一个 Students 实体:

       选择 hibernate.cfg.xml 右键,选择创建实体Entity(记得 要先按照上回讲到的,创建相应的 Hibernate 的配置文件 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">create</property>

        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

):

       选择在 entity 包下创建:

       创建成功后,在Hibernate配置文件中会自动添加一行映射关系:

       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,会看如下运行结果:
       在 名为 hibernate 的数据库下 创建了 Students 表,并插入了一条数据。


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值