使用hibernate的准备工作。
一 导入Hibernate 相关jar包和数据库驱动。
二 新建项目,在src文件中导入hibernate.cfg.xml 总配置文件
log4j.properties 日志文件
Hibernate支持两种配置文件格式:hibernate.properties和hibernate.cfg.xml,大概xml形式用的比较多。现在以 xml形式为例。
1 配置文件配置相关信息
1 <hibernate-configuration> 2 <session-factory> 3 <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property> //连接路径 4 <propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> //mysql驱动 5 <property name="hibernate.connection.username">root</property> //数据库用户名 root 6 <property name="hibernate.connection.password">123</property> //数据库密码 123 7 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> //方言 8 <property name="hibernate.show_sql">true</property> //显示sql语句 9 <property name="format_sql">true</proterty> //sql语句自动换行 10 <mapping resource="com/Test/po/User.hbm.xml"/> 11 </session-factory> 12 </hibernate-configuration>
2 测试是否配置成功
public class Test extends TestCase { public void Test1() throws Exception{ Configuration config= new Configuration().configure(); //加载xml格式配置文件,如果加载properties格式配置文件,将.configure()去掉既可。 SessionFactory sessionFactory=config.buildSessionFactory(); //建立连接工厂 Session session=sessionFactory.openSession(); // 建立连接 System.out.println("连接成功"); session.close();// 关闭连接 sessionFactory.close();//关闭链接工厂 } }
SessionFactory :连接工厂,只有一个,初始化一次,管理二级缓存,产生连接。
Session:表示连接,管理一级缓存,开启事务。
3建user 类
public class User { private String name; private String pwd; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
4 建立User的映射映射文件User.hbm.xml
<hibernate-mapping > <class name="com.Test.po.User" table="user"> 映射的类名和表名 <id name="id" column="id"> <generator class="native"></generator> //id生成策略 </id> <property name="name" column="name"></property> 属性name 对应表字段name <property name="pwd" column="pwd" ></property> </class> </hibernate-mapping>
映射文件写好后,要在总配置文件中添加映射的路径,<mapping resource="com/Test/po/User.hbm.xml"/>
Hibernate 通过映射文件产生sql语句
5 导表测试
public void Test2() throws Exception{ Configuration config=new Configuration().configure(); //加载总配置文件 SchemaExport export= new SchemaExport(config); // 对导表工具类初始化 export.create(true, true); // 第一个参数:是否打印建表语句 第二个参数:是否之行建表语句。 }
导表时,配置文件中有多少<mapping>就导出多少表。
6 查看数据库是否已建好表User
drop table if exists user create table user (id integer not null auto_increment, name varchar(255), pwd varchar(255), primary key (id))
+-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | pwd | varchar(255) | YES | | NULL | | +-------+--------------+------+-----+---------+----------------+
|