这个程序,我用的是3.3.2版本的。一开始就下载的是hibernate5.0.30,发现教程要比经典版本的少很多,而且出了错很难找到答案,调试第一个程序许久也没结果,于是就换成了3.3.2版本。因此,若是读者的hibernate版本与我的版本差别较大,希望读者不要在这里浪费太多时间。
我的第一个程序是将一个对象通过hibernate来写入mysql。
1.导包,很简单
2.写javabean:Student.java,以及其对应的解析文件Student.hbm.xml ,两者放在同一包下。
javabean里属性的名称与mysql 里创建的表的列名称 以及 对应的类型 应该匹配。
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.wanhao">
<class name="Student">
<id name="id"></id>
<property name="name"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
这里就显示出 我曾经说的,尽量把mysql的列名与javabean的属性名设为一致,类型必须一致。
若是mysql的列名为 _id,而javabean对应的属性名为 id ,则要这样写 <id name="id" column="_id"></id> ,
表示这张表的主键 _id 对应属性名 id。而若是两者一致,则简化代码。
3.hibernate.cfg.xml 放在src目录下,作为配置文件。
<?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/student</property>
<property name="connection.username">填写数据库的名称</property>
<property name="connection.password">填写数据库密码</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property>-->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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/wanhao/Student.hbm.xml"/> // 表示第二步建的相应的 javabean 的配置文件的具体地址,相对的。
</session-factory>
</hibernate-configuration>
4.然后便是驱动类,Test类
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.wanhao.Student;
public class Test {
public static void main(String[] args)
{
Student stu=new Student();
stu.setAge(10);
stu.setId(1);
stu.setName("wanhao");
Configuration cfg=new Configuration();
SessionFactory sf=cfg.configure().buildSessionFactory();
Session sess=sf.openSession();
sess.beginTransaction();
sess.save(stu);
sess.getTransaction().commit();
sess.close();
sf.close();
System.out.println("SUCCESS");
}
}