<?xml version="1.0" encoding="GBK"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="javamxj.hibernate.User" table="UserTable"> <id name="id"> <generator class="assigned" /> </id> <property name="username" /> <property name="password" /> </class> </hibernate-mapping>
<?xml version='1.0' encoding='GBK'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"> <hibernate-configuration> <session-factory> <!-- 是否将运行期生成的SQL输出到日志以供调试 --> <property name="show_sql">true</property> <!-- SQL方言,这里设定的是MySQL --> <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property> <!-- JDBC驱动程序 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- JDBC URL, "?useUnicode=true&characterEncoding=GBK" 表示使用GBK进行编码 --> <property name="connection.url"> jdbc:mysql://localhost:3306/HibernateTest?useUnicode=true&characterEncoding=GBK </property> <!-- 数据库用户名 --> <property name="connection.username">root</property> <!-- 数据库密码 --> <property name="connection.password">javamxj</property> <!-- 指定User的映射文件 --> <mapping resource="javamxj/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration>
注意:这里使用的是“jdbc:mysql://localhost:3306/HibernateTest?useUnicod...”中的HibernateTest数据库,你需要在
MySql中建立这个数据库。
5. 测试程序
在javamxj.hibernate包下,新建一个Test类,内容如下:
/* * 简单测试一下User类 * 创建日期 2005-3-31 * @author javamxj(分享java快乐) */ package javamxj.hibernate; import net.sf.hibernate.*; import net.sf.hibernate.cfg.*; public class Test { public static void main(String[] args) { try { SessionFactory sf = new Configuration().configure() .buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); User user = new User(); user.setUsername("Blog"); user.setPassword("分享java快乐"); session.save(user); tx.commit(); session.close(); } catch (HibernateException e) { e.printStackTrace(); } } }
CREATE TABLE usertable (
ID int(6) NOT NULL auto_increment,
username varchar(24) NOT NULL default '',
password varchar(24) NOT NULL default '',
PRIMARY KEY (ID)
);
