初学Hibernate框架之环境配置和测试

来源:互联网 发布:尤里的复仇数据修改 编辑:程序博客网 时间:2024/05/17 02:33

      想学习一下使用SSH框架做一个简单的网站开发,所以决定从与数据库最相关的Hibernate开始学起。学习参考的主要是:Hibernate 入门教程(纯Eclipse版)。在这里记录一下学习的步骤和其中遇到的各种问题。

第一步:导包

      首先在网上下载了hibernate-distribution-3.6.10.Final,将其中的hibernate3.jar、lib/required下面的jar包、连接mysql数据库的mysql-connector-java-5.0.8-bin.jar都导入了lib文件夹里。

第二步:创建实体类的类以及对应的映射关系的xml。

package com.hibernate;/* * user用户实体类 */public class User {private String userId;private String userPassword;public User() {super();}public User(String userId, String userPassword) {super();this.userId = userId;this.userPassword = userPassword;}public String getUserPassword() {return userPassword;}public void setUserPassword(String userPassword) {this.userPassword = userPassword;}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}}

<?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 package="com.hibernate"><class name="User" table="sys_user"><id name="userId" type= "java.lang.String" column="USER_ID"> <generator class="assigned" /></id><property name="userPassword" type="java.lang.String" column="USER_PASSWORD" /></class></hibernate-mapping>
第三步:hibernate配置的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"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">org.gjt.mm.mysql.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/secondarytradingplatform?useUnicode=true&characterEncoding=UTF-8</property><property name="connection.username">root</property><property name="connection.password">root</property><!-- JDBC connection pool (use the built-in) --><property name="connection.pool_size">1</property><!-- SQL dialect --><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><!-- Drop and re-create the database schema on startup --><property name="hbm2ddl.auto">update</property><mapping resource="com/hibernate/User.hbm.xml" /></session-factory></hibernate-configuration>  
第四步:创建hibernate工厂类

package com.hibernate.factory;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static final SessionFactory sessionFactory = buildSessionFactory();        private static SessionFactory buildSessionFactory() {          try {              // Create the SessionFactory from hibernate.cfg.xml              return new Configuration().configure().buildSessionFactory();          }          catch (Throwable ex) {              // Make sure you log the exception, as it might be swallowed              System.err.println("Initial SessionFactory creation failed." + ex);              throw new ExceptionInInitializerError(ex);          }      }        public static SessionFactory getSessionFactory() {          return sessionFactory;      }  }
第五步:写测试类进行测试

package com.cn.service;import org.hibernate.classic.Session;import com.hibernate.User;import com.hibernate.factory.HibernateUtil;public class UserRegister {public static void main(String[] args) {UserRegister mgr = new UserRegister();mgr.createAndStoreEvent("superadmin", "admin");HibernateUtil.getSessionFactory().close();}private void createAndStoreEvent(String userId, String userPassword) {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();User user = new User();user.setUserId(userId);user.setUserPassword(userPassword);session.save(user);session.getTransaction().commit();}}
结果:在数据库中插入成功


这样一个简单的hibernate的使用环境的配置OK并可以使用了。


其中遇到的问题:

1.导包不全的问题:开始看到需要slf4j包,然后看到已有slf4j-api-1.6.1.jar,就以为可以了,运行时发现报错,导入slf4j-nop-1.6.1.jar就OK了。slf4j的包导入完成后,又出现了新的问题,上网搜了一下原来需要hibernate-jpa-2.0-api-1.0.1.Final.jar...

2.实体类对应的XML的写法:类型开始用的是String,报错:Could not determine type for: String, at table: sys_user, for columns: [org.hibernate.mapping.Column(USER_PASSWORD)]---->将类型改成java.lang.String成功解决...

3.实体类对应的XML中每个属性的name属性需要与实体类中的属性名相同,column对应数据库中的字段名,主键与其他的写法不同...







0 0
原创粉丝点击