一个用myeclipse开发hibernate的入门例子

本文介绍如何使用Hibernate框架实现Java应用程序与MySQL数据库之间的交互。包括搭建开发环境、创建实体类及映射文件、配置SessionFactory以及编写测试代码等关键步骤。
部署运行你感兴趣的模型镜像
 一、环境

1.eclipse 3.2.2
2.myeclipse 5.1.1
3.jdk 1.5

二、简要说明

数据库为mysql

 在mysql中建立一个test数据库,建立cat表
CREATE TABLE `cat` (
  `cat_id` varchar(32) NOT NULL,
  `name` varchar(16) NOT NULL,
  `sex` varchar(1) default NULL,
  `weight` float(9,3) default NULL,
  PRIMARY KEY  (`cat_id`)
)

三、步骤

1.导入包的准备工作

a.新建java project.建立包example
在它下面编写类Cat.java

package example;

 public class Cat  implements java.io.Serializable {


    // Fields   

     private String catId;
     private String name;
     private String sex;
     private Float weight;


    // Constructors

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

 /** minimal constructor */
    public Cat(String name) {
        this.name = name;
    }
   
    /** full constructor */
    public Cat(String name, String sex, Float weight) {
        this.name = name;
        this.sex = sex;
        this.weight = weight;
    }

  
    // Property accessors

    public String getCatId() {
        return this.catId;
    }
   
    public void setCatId(String catId) {
        this.catId = catId;
    }

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

    public String getSex() {
        return this.sex;
    }
   
    public void setSex(String sex) {
        this.sex = sex;
    }

    public Float getWeight() {
        return this.weight;
    }
   
    public void setWeight(Float weight) {
        this.weight = weight;
    }  
}

同样在此包下面编写Cat.hbm.xml

   <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
" http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="example.Cat" table="cat" catalog="testhibernate">
        <id name="catId" type="java.lang.String">
            <column name="cat_id" length="32" />
            <generator class="uuid.hex"></generator>
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="16" not-null="true" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" length="1" />
        </property>
        <property name="weight" type="java.lang.Float">
            <column name="weight" precision="9" scale="3" />
        </property>
    </class>
</hibernate-mapping>

b.在工程的src里面加入一个包,用来存放将要生成的HibernateSessionFactory。包名如(example.util)。
导入hibernate(生成的代码:
package example.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * 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 String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    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(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } 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 session factory
     *
     * session factory will be rebuilded in the next call
     */
 public static void setConfigFile(String configFile) {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 /**
     *  return hibernate configuration
     *
     */
 public static Configuration getConfiguration() {
  return configuration;
 }

}

对工程名点鼠标右键。选择myeclipse->add

hibernate capabicities。

在弹出的窗口选择中Hibernate 3.0 Core Libraries和Hibernate 3.0 Advanced Support Libraries

下面选中Copy checked Library Jars to project folder and add to build-path。点击下一步。

c.默认(hibernate cofig file),下一步。

d.选中User JDBC driver
connect url:  jdbc:mysql://localhost:3306/test
Driver class:  org.gjt.mm.mysql.Driver
username:  root
password: ******
Dialect: mysql

e.在第一行包选择里面,选择在前面第二大步建的包如(example)。点击完成。

f.弹出的画面中 选择properties的add按钮。在Property中加入show_sql,Value中加入true。点确定

保存设置。在mappings中点add加入前面建立的Cat.hbm.xml。最后生成的hibernate.cfg.xml文件如下
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
 <property name="connection.username">root</property>
 <property name="connection.url">
  jdbc:mysql://localhost:3306/testhibernate
 </property>
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <property name="connection.password">123456</property>
 <property name="connection.driver_class">
  org.gjt.mm.mysql.Driver
 </property>
 <property name="show_sql">true</property>
 <mapping resource="example/Cat.hbm.xml" />

</session-factory>

</hibernate-configuration>


3.测试 新建包test 在其中建立测试文件TestHibernate.java
package test;

import java.util.Iterator;
import java.util.List;
import example.*;
import example.util.*;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class TestHibernate {
 Session session=null;
 Transaction tx=null;
public static void main(String[] args) {
 TestHibernate th=new TestHibernate(); 
 List cl=th.getAllCats();
 if(cl!=null){
  Iterator it=cl.iterator();
  while(it.hasNext()){
   Cat cat=(Cat)it.next();
   System.out.println("catID:"+cat.getCatId()+"name:"+cat.getName()+"sex:"+cat.getSex());
  }
 }
  
  

 }
public List getAllCats(){
 session=HibernateSessionFactory.getSession();
 List catlist=null;
 try{
  tx=session.beginTransaction();
  catlist=session.createQuery("from Cat").list();
  return catlist;
 }catch(Exception ex){
  System.err.println(ex.getMessage());
  return null;
 }finally{
  HibernateSessionFactory.closeSession();
 }
}

}

 

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

内容概要:本文介绍了ENVI Deep Learning V1.0的操作教程,重点讲解了如何利用ENVI软件进行深度学习模型的训练与应用,以实现遥感图像中特定目标(如集装箱)的自动提取。教程涵盖了从数据准备、标签图像创建、模型初始化与训练,到执行分类及结果优化的完整流程,并介绍了精度评价与通过ENVI Modeler实现一键化建模的方法。系统基于TensorFlow框架,采用ENVINet5(U-Net变体)架构,支持通过点、线、面ROI或分类图生成标签数据,适用于多/高光谱影像的单一类别特征提取。; 适合人群:具备遥感图像处理基础,熟悉ENVI软件操作,从事地理信息、测绘、环境监测等相关领域的技术人员或研究人员,尤其是希望将深度学习技术应用于遥感目标识别的初学者与实践者。; 使用场景及目标:①在遥感影像中自动识别和提取特定地物目标(如车辆、建筑、道路、集装箱等);②掌握ENVI环境下深度学习模型的训练流程与关键参数设置(如Patch Size、Epochs、Class Weight等);③通过模型调优与结果反馈提升分类精度,实现高效自动化信息提取。; 阅读建议:建议结合实际遥感项目边学边练,重点关注标签数据制作、模型参数配置与结果后处理环节,充分利用ENVI Modeler进行自动化建模与参数优化,同时注意软硬件环境(特别是NVIDIA GPU)的配置要求以保障训练效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值