hibernate使用myeclise简化开发----根据数据库及表反向生成代码信息

前面我们讲的都是新建一个java项目,然后写实体类,映射文件或注解,然后关联到hibernate.cfg.xml中,然后根据hbm文件生成数据库表,这节我们就反过来实现这个过程----也就是说,我们新建一个项目后,根据数据库和表来生成hibernate.cfg.xml文件、实体类和映射文件或注解,包括jar包都有myeclipse来替我们引入。具体步骤如下:


myeclipse和数据库关联


新建一个java项目,如图:



打开DB Browser如图:



鼠标右键new,如图:



在弹出的连接数据库的框中,添加完成连接数据库的信息,测试通过后,点finish



可以在DB Browser中看到刚刚新建的mysql数据库,如图:



项目和数据库关联--反向生成


myeclipse和mysql数据库hibernate4的连接已经完成,下面开始将项目和数据库挂钩,

具体步骤如下:





点击next:


继续点击next:



点next:



点击finish,myeclipse替我们生成了HibernateSessionFactory、hibernate.cfg.xml以及导入了hibernate的核心jar包:



HibernateSessionFatory代码:

package com.myeclipse.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

	static {
    	try {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}


hibernate.cfg.xml配置文件代码:


<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="myeclipse.connection.profile">mysql</property>
    
    </session-factory>

</hibernate-configuration>


数据库表生成实体类


接下来我们就可以利用数据库表来生成项目实体类代码以及配置文件或者是注解,步骤如下:

现在数据库hibernate4中生成两种数据库表,

一张是类目表Category,一张是图书表t_book,图书表t_book中关联了category表的主键作为外键

如图:



选择DB Browser界面,







1)生成*.hbm.xml形式代码


先演示生成*.hbm.xml配置文件的形式,所以勾选如上图所示,生成的项目结构如下图:




对应的代码是:

Catagory代码:

package com.myeclipse.pojo;

import java.util.HashSet;
import java.util.Set;

/**
 * Category entity. @author MyEclipse Persistence Tools
 */

public class Category implements java.io.Serializable {

	// Fields

	private Integer id;
	private String name;
	private Set TBooks = new HashSet(0);

	// Constructors

	/** default constructor */
	public Category() {
	}

	/** full constructor */
	public Category(String name, Set TBooks) {
		this.name = name;
		this.TBooks = TBooks;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getTBooks() {
		return this.TBooks;
	}

	public void setTBooks(Set TBooks) {
		this.TBooks = TBooks;
	}

}


Category.hbm.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd ">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.myeclipse.pojo.Category" table="category" catalog="hibernate4">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <set name="TBooks" inverse="true">
            <key>
                <column name="categry_id" />
            </key>
            <one-to-many class="com.myeclipse.pojo.TBook" />
        </set>
    </class>
</hibernate-mapping>

TBook代码:

package com.myeclipse.pojo;

import java.sql.Timestamp;

/**
 * TBook entity. @author MyEclipse Persistence Tools
 */

public class TBook implements java.io.Serializable {

	// Fields

	private Integer id;
	private Category category;
	private String author;
	private String bookName;
	private Double price;
	private Timestamp pubDate;

	// Constructors

	/** default constructor */
	public TBook() {
	}

	/** full constructor */
	public TBook(Category category, String author, String bookName,
			Double price, Timestamp pubDate) {
		this.category = category;
		this.author = author;
		this.bookName = bookName;
		this.price = price;
		this.pubDate = pubDate;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Category getCategory() {
		return this.category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public String getAuthor() {
		return this.author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getBookName() {
		return this.bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public Double getPrice() {
		return this.price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public Timestamp getPubDate() {
		return this.pubDate;
	}

	public void setPubDate(Timestamp pubDate) {
		this.pubDate = pubDate;
	}

}


TBook.hbm.xml代码:


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd ">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.myeclipse.pojo.TBook" table="t_book" catalog="hibernate4">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <many-to-one name="category" class="com.myeclipse.pojo.Category" fetch="select">
            <column name="categry_id" />
        </many-to-one>
        <property name="author" type="java.lang.String">
            <column name="author" />
        </property>
        <property name="bookName" type="java.lang.String">
            <column name="book_name" />
        </property>
        <property name="price" type="java.lang.Double">
            <column name="price" precision="22" scale="0" />
        </property>
        <property name="pubDate" type="java.sql.Timestamp">
            <column name="pubDate" length="19" />
        </property>
    </class>
</hibernate-mapping>


hibernate.cfg.xml代码关联如图:



2)生成注解和实体类

从DB Browser界面,选择表,右键,


finish,生成的实体类结构如图:



对应的Category实体类和注解代码:

package com.myeclipse.pojo;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Category entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "category", catalog = "hibernate4")
public class Category implements java.io.Serializable {

	// Fields

	private Integer id;
	private String name;
	private Set<TBook> TBooks = new HashSet<TBook>(0);

	// Constructors

	/** default constructor */
	public Category() {
	}

	/** full constructor */
	public Category(String name, Set<TBook> TBooks) {
		this.name = name;
		this.TBooks = TBooks;
	}

	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name = "name")
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
	public Set<TBook> getTBooks() {
		return this.TBooks;
	}

	public void setTBooks(Set<TBook> TBooks) {
		this.TBooks = TBooks;
	}

}

生成的TBook实体类及注解代码:


package com.myeclipse.pojo;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * TBook entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "t_book", catalog = "hibernate4")
public class TBook implements java.io.Serializable {

	// Fields

	private Integer id;
	private Category category;
	private String author;
	private String bookName;
	private Double price;
	private Timestamp pubDate;

	// Constructors

	/** default constructor */
	public TBook() {
	}

	/** full constructor */
	public TBook(Category category, String author, String bookName,
			Double price, Timestamp pubDate) {
		this.category = category;
		this.author = author;
		this.bookName = bookName;
		this.price = price;
		this.pubDate = pubDate;
	}

	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "categry_id")
	public Category getCategory() {
		return this.category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	@Column(name = "author")
	public String getAuthor() {
		return this.author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	@Column(name = "book_name")
	public String getBookName() {
		return this.bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	@Column(name = "price", precision = 22, scale = 0)
	public Double getPrice() {
		return this.price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	@Column(name = "pubDate", length = 19)
	public Timestamp getPubDate() {
		return this.pubDate;
	}

	public void setPubDate(Timestamp pubDate) {
		this.pubDate = pubDate;
	}

}


hibernate.cfg.xml关联注解实体类代码如图:










  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值