菜鸟级Hibernate入门心得
我之前没有学过Hibernate,甚至都没有用过JSP,Servlet做一些东西,一直学的是C#,asp.net,但是在看.net项目源码的时候发现,作者使用ORM技术,当时看得一头雾水,在网上搜了一下,原来是是与Hibernate相关的一门构架思想,所以就去图书馆借了一本书《深入浅出Hibernate》,看完第一张,觉得基本上都明白,因为之前了解过一些设计模式的知识。第二章讲解入门级Hibernate配置,以下是我遇到的困难和解决方案,写出来与大家共勉,如果不对之处,欢迎指正。
准备工作:
1.软件:
IDE:eclipse-jee-galileo-win32.zip
DataBase:mysql5.1.30win32.zip
DataBase View:MySQLFront-v5.1.357.zip
2.源文件:
hibernate-2.1.8.zip
hibernate-extensions-2.1.3.zip
Middlegen-Hibernate-r5.zip
mysql-connector-java-5.0.3-bin.jar
1.哪里下载Hibernate
这个问题我困惑了很久,在sourceforge上不知道怎么下载。不过还是会了,这个比较简单,就不多说,自己去找!
2.有数据库产生基础代码
use hibsql;
CREATE TABLE `t_user1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
新建了一个java项目,把hibernate等一下文件拷到了lib文件下。
3.如何产生MiddleGen画面和生成*.hbm.xml文件
a)首先配置MiddleGen所需要的目标数据库参数:
进入Middlegen-Hibernate-r5\config\database\mysql.xml,修改数据库配置文件,包括数据库名称,数据库用户名和密码。
<!-- =================================================================== --> <!-- ant properties/targets for mysql --> <!-- note: this is not a proper xml file (there is no root element) --> <!-- it is intended to be imported from a *real* xml file --> <!-- =================================================================== --> <property name="database.script.file" value="${src.dir}/sql/${name}-mysql.sql"/> <property name="database.driver.file" value="${lib.dir}/mysql-connector-java-5.0.3-bin.jar"/> <property name="database.driver.classpath" value="${database.driver.file}"/> <property name="database.driver" value="org.gjt.mm.mysql.Driver"/> <property name="database.url" value="jdbc:mysql://localhost/hibsql"/> <property name="database.userid" value="root"/> <property name="database.password" value="sunbin123"/> <property name="database.schema" value=""/> <property name="database.catalog" value=""/> <property name="jboss.datasource.mapping" value="mySQL"/>
<!DOCTYPE project [ <!ENTITY database SYSTEM "file:./config/database/mysql.xml">]>
<path id="lib.class.path"> <pathelement path="${database.driver.classpath}"/> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> <!-- The middlegen jars --> <!--fileset dir="${basedir}/.."--> <fileset dir="${basedir}/middlegen-lib"> <include name="*.jar"/> </fileset> <pathelement path="../hibernate-2.1/hibernate2.jar"/> <fileset dir="../hibernate-2.1/lib"><include name="*.jar"/> </fileset> <pathelement path="../hibernate-extensions-2.1.3/tools/hibernate-tools.jar"/> <fileset dir="../hibernate-extensions-2.1.3/tools/lib"><include name="*.jar"/> </fileset> </path>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"><hibernate-configuration><session-factory><!-- 各属性的配置--><!-- 数据库URL --><property name="hibernate.connection.url">jdbc:mysql://localhost/hibsql</property><!-- 数据库JDBC驱动 --><property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property><!-- 数据库用户名 --><property name="hibernate.connection.username">root</property><!-- 数据库密码 --><property name="hibernate.connection.password">sunbin123</property><!-- dialect,每个数据库都有其对应的dialect以匹配其平台特性--><property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property><!-- 是否将运行期生成的SQL输出到日志以供调试 --><property name="show_sql">true</property><!-- 是否使用数据库外连接 --><property name="hibernate.use_outer_join">True</property><!-- 事务管理类型,这里我们使用JDBC Transaction --><property name="hibernate.transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</property><!-- 映射文件 --><mapping resource="org/redsaga/quickstart/Tuser.hbm.xml"/> </session-factory></hibernate-configuration>
import java.util.List;import org.redsaga.quickstart.TUser;import junit.framework.Assert;import junit.framework.TestCase;import net.sf.hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory;import net.sf.hibernate.Transaction;import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate.cfg.Environment;public class HibernateTest extends TestCase{Session session = null;protected void setUp(){try{//Configuration config = new Configuration();//config.addClass(Tuser.class);Configuration config = new Configuration().configure();SessionFactory sessionFactory = config.buildSessionFactory();session = sessionFactory.openSession();}catch(HibernateException e){e.printStackTrace();}}protected void tearDown(){try{session.close();}catch(HibernateException e){e.printStackTrace();}}public void testInsert(){Transaction tran = null;try{tran = session.beginTransaction();TUser user = new TUser();user.setName("sunbin");session.save(user);session.flush();tran.commit();Assert.assertEquals(user.getId().intValue()>0, true);}catch(HibernateException e){e.printStackTrace();Assert.fail(e.getMessage());if(tran!=null){try{tran.rollback();}catch(HibernateException e1){e1.printStackTrace();}}}}public void testSelect(){String hql = " from TUser where name='sunbin'";try{List userlist = session.createQuery(hql).list();TUser user = (TUser)userlist.get(0);System.out.print("共有"+userlist.size()+"条记录");System.out.print(user.getName());Assert.assertEquals(user.getName(), "sunbin");}catch(HibernateException e){e.printStackTrace();Assert.fail(e.getMessage());}}}