Hibernate 环境 配置 映射数据库 SQL server ,Mysql 数据库 ,测试无误

最近要消化的知识有点多,多以特地将笔记写道 博客中,方便查看
需要到的hibernate jar 包 ,大家可以自行到官网下载

Hibernate 中 配置 Sqlserver 数据库

<?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">
 <hibernate-configuration>
    <session-factory>
        <!-- 配置数据库JDBC驱动  -->
        <property name="hibernate.connection.url">jdbc:sqlserver://localhost:50044;DatabaseName=NetData</property>
        <!-- 配置数据库连接url -->
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <!-- 配置数据库用户名 -->
        <property name = "hibernate.connection.username">sa</property>
        <!-- 配置数据库密码 -->
        <property name = "hibernate.connection.password">xxxxxx</property>
        <!-- 输出运行时生成sql语句 -->
        <property name="show_sql">true</property>
        <!-- 配置数据库方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <!-- 配置连接池数量 -->
        <property name="hibernate.jdbc.batch_size">16</property>
        <!-- 列出映射文件 -->
        <mapping resource="com/javaBean/Card.hbm.xml"/>
    </session-factory>

 </hibernate-configuration>

列出映射文件mapping 是要准确映射到 javabean中的 xxx.hbm.xml 文件,在写完映射的时候可以用Ctrl + 鼠标箭头最准 看看是否能映射到 xxx.hbm.xml 文件

Card.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">
 <hibernate-mapping>
 <!-- 对持久化类Card的映射的配置 -->
    <class name="com.javaBean.Card" table="Card">
    <!--  -->
        <id name="ID" column="ID" type="string">
            <generator class="assigned"/>
        </id>

        <property name="Password" type="string" not-null="true" length="50">
            <column name="Password"/>
        </property>

        <property name="Balance" type="int" not-null="true">
            <column name="Balance"/>
        </property>

        <property name="UserName" type="string" not-null="true" length="50">
            <column name="UserName"/> 
        </property>
    </class>
 </hibernate-mapping>

这样子 配置,再将hibernate 的环境配置好,命名一个HibernateInitialize类,实现方法如下:

package com.Hibernate;

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

public class HibernateInitialize {
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory = null;//SessionFactory对象
    static {
        try{
            //加载Hibernate配置文件
            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();//实例化SessionFactory对象
        }catch(Exception e) {
            System.err.println("创建会话工厂失败");
            e.printStackTrace();
        }
    }
    /**
     *  获取Session
     *  @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;
    }
    /**
     * 重建会话工厂
     */
    private static void rebuildSessionFactory() {
        // TODO 自动生成的方法存根
        try {
            // 加载Hibernate配置文件
            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();
        }catch(Exception e) {
            System.out.println("重建会话工厂失败");
            e.printStackTrace();
        }
    }
    /**
     * 获取SessionFactory对象
     * @return SessionFactory对象
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /** 
     *  关闭Session
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException{
        Session session =(Session)threadLocal.get();
        threadLocal.set(null);
        if(session != null) {
            session.close();
        }
    }
}

Hibernate 中 配置 MySQL数据库

<?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">
 <hibernate-configuration>
    <session-factory>
        <!-- 配置数据库连接url -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 配置数据库JDBC驱动 -->
        <property name ="connection.url">jdbc:mysql://xxx.xxx.xxx.xxx:3306/wcmdb</property>
        <!-- 配置数据库名称 -->
        <property name = "connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name = "connection.password">xxxxx</property>
        <!-- Hibernate 方言 -->
        <property name = "dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印sql语句 -->
        <property name="show_sql">true</property>
        <!-- 连接池大小 -->  
        <property name="connection.pool_size">1</property>  
        <!-- 映射文件 -->
        <mapping  resource="com/javaBean/Login.hbm.xml"/>
        <mapping  resource="com/javaBean/Goods.hbm.xml"/>
    </session-factory>
 </hibernate-configuration>

具体实现:

Session session=null;
try {
            session=HibernateInitialize.getSession();

            Query q = session.createSQLQuery("select * from goods").addEntity(Goods.class);

            @SuppressWarnings("unchecked")
            List<Goods> ls = q.list();

            for(Goods li : ls) {
                System.out.println( li.getId() +"," +li.getGoodsname() +","+li.getPrice() +"," +li.getPicture() );
            }   

            req.setAttribute("ls",ls);
            req.getRequestDispatcher("/GoodsInfo.jsp").forward(req, resp);

        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            HibernateInitialize.closeSession();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
private static void printTableMetaInfo(Session session) { Connection connection = session.connection(); try { DatabaseMetaData metaData = connection.getMetaData(); ResultSet result = metaData.getColumns(null, null, NameOfTable, null); String strInJava = ""; String typeInJava; while (result.next()) { String columnName = result.getString(4); if ("stampTime".equalsIgnoreCase(columnName)) { continue; } int columnType = result.getInt(5); String nameFirstLetterLower = columnName.substring(0, 1).toLowerCase() + columnName.substring(1); switch (columnType) { case Types.VARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.NVARCHAR: case Types.CHAR: typeInJava = "String"; break; case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: typeInJava = useInteger ? "Integer" : "int"; break; case Types.TIMESTAMP: case Types.BINARY: typeInJava = "Calendar"; break; case Types.DECIMAL: typeInJava = "BigDecimal"; break; case Types.BIGINT: typeInJava = "BigInteger"; break; case Types.LONGVARBINARY: typeInJava = "byte[]"; break; case Types.DATE: typeInJava = "Calendar"; break; default: throw new Exception("Unknown type " + columnType + " and column is " + columnName); } strInJava += " private " + typeInJava + " " + nameFirstLetterLower + ";\n"; // strInHibernate += "\n"; } String str = "import javax.persistence.Entity;\n" + "import javax.persistence.Id;\n" + "import javax.persistence.Table;\n" + "import java.util.Calendar;\n\n"; str += "@Entity\n"; str += "@Table(name=\"$\")\n".replace("$", NameOfTable); str += "public class $ {\n".replace("$", NameOfTable.substring(2)); str += "\n @Id\n"; str += strInJava; str += "}"; System.out.println(str); StringSelection stringSelection = new StringSelection(str); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); } catch (Exception e) { e.printStackTrace(); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值