Hibernate入门学习(二):Hibernate所涉及的文件
HIbernate有这么几个主角:
pojo.java
pojo.hbm.xml
hibernate.cfg.xml(或hibernate.perperty)
pojo.java:这个类是个JavaBean。为什么要有个JavaBean呢?因为每个数据库的表必须有个和它对应的对象,这样Hibernate才能利用对象的属性把数据插入到数据库中。因此就必须每个数据库表对应一个,这个JavaBean就是pojo类。
实例UserInfo.java:
public class UserInfo { private Integer id; private String name; private String password;public Integer getId() {return id;}private void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
*.hbm.xml:有个pojo类还不够,因为Hibernate还不能把java类和数据库对应起来.Hibernate的解决方法是将类与数据库的关联信息配置在一个*.hbm.xml文件里。
比如,UserInfo.java对应数据表users,则这个表中的哪个属性对应数据库中这个表中的哪个字段,字段长度,id应该怎么增加,都配置在这个*.hbm.xml中。
实例Users.hbm.xml:
<hibernate-mapping> <class name="com.dodo1988.UserInfo" table="users"> <id name="id" type="integer"> <column name="id" /> <generator type="string"> <column name="name" length="20" /> </property> <property name="password" type="string"> <column name="password" length="20" /> </property> </class></hibernate-mapping>
补充说明:
1.当class的name和table的name一样时,table的name可以省略不写;
2.id标识的是数据表主键与类属性的关系映射,property标识的是非主键的关系映射;
3.id的name值是类中的属性,column的name值是表中的字段名;
4.当id的name和column的name值一样时,column的name值可以省略不写;
5.property的略写规则同上;
6.名称中的hbm是hibernate mapping的缩写,恰如其名吧。
hibernate.cfg.xml:其中配置一些全局信息,如:数据库的url,数据库账户,密码。数据库类型,驱动所在的uri,操作之后是否显示sql语句等。
实例hibernate.cfg.xml:
<session-factory><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/test</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.username">root</property><property name="connection.password">dodo</property><property name="show_sql">true</property><property name="connection.pool_size">15</property><mapping resource="Users.hbm.xml" /></session-factory>
hibernate.perperty:与hibernate.cfg.xml存储的信息类似,只不过在读取时使用的方法不一样。
实例hibernate.perperty:
hibernate.dialect org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class com.mysql.jdbc.Driverhibernate.connection.url jdbc:mysql://localhost:3306/testhibernate.connection.username roothibernate.connection.password dodo
本节参考视频教程:
下载:http://ishare.iask.sina.com.cn/f/9732846.html