昨天我们进行了hibernate的配置,并且进行了根据ID查询对应数据的操作,今天我们来看看hibernate中的几个配置文件,里面到底有什么东东。
一、hibernate.cfg.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<
hibernate-configuration
>
<
session-factory
>
<
property
name
=
"dialect"
>
org.hibernate.dialect.MySQLDialect
</
property
>
<
property
name
=
"connection.url"
>
jdbc:mysql://127.0.0.1:3306/superktv
</
property
>
<
property
name
=
"connection.username"
>root</
property
>
<
property
name
=
"connection.password"
>root</
property
>
<
property
name
=
"connection.driver_class"
>
com.mysql.jdbc.Driver
</
property
>
<
property
name
=
"myeclipse.connection.profile"
>mysql</
property
>
<
mapping
resource
=
"com/pxy/dao/Author.hbm.xml"
/>
</
session-factory
>
</
hibernate-configuration
>
|
这里面应该没有什么不好懂的吧,就注意一点,<mapping>标签的路径不要引用错了,每次引用完后,记得按住Ctrl键,再把鼠标移动到resource的值上去,如果双引号里的内容变成了超链接,那说明没问题。当然,如果你是通过DBBrowser生成的文件,那肯定不会引用错误。
二、Author.hbm.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<
hibernate-mapping
>
<
class
name
=
"com.pxy.entity.Author"
table
=
"author"
catalog
=
"blogdb"
>
<
id
name
=
"id"
type
=
"java.lang.Integer"
>
<
column
name
=
"id"
/>
<
generator
class
=
"native"
/>
</
id
>
<
property
name
=
"username"
type
=
"java.lang.String"
>
<
column
name
=
"username"
length
=
"20"
not-null
=
"true"
/>
</
property
>
<
property
name
=
"password"
type
=
"java.lang.String"
>
<
column
name
=
"password"
length
=
"10"
not-null
=
"true"
/>
</
property
>
<
property
name
=
"email"
type
=
"java.lang.String"
>
<
column
name
=
"email"
length
=
"20"
/>
</
property
>
<
property
name
=
"address"
type
=
"java.lang.String"
>
<
column
name
=
"address"
length
=
"20"
/>
</
property
>
<
property
name
=
"phone"
type
=
"java.lang.String"
>
<
column
name
=
"phone"
length
=
"20"
/>
</
property
>
</
class
>
</
hibernate-mapping
>
|
class标签的name表示对应的实体类,table表示对应的数据表,catalog表示对应的数据库。
id标签:表示主键。
generator标签:主键的生成策略。
property标签:表示实体类的属性。
column标签:表示对应表中的字段。
对于单个对象的操作,我们上次已经用过了load方法,除此之外,常用的还有以下四个:
get()方法,save()方法,update()方法,delete()方法
从名字就应该可以猜出对应的用法吧,这儿就不在一一演示了,各位看官自行解决吧·
最后简单说一下load()和get()的区别:
load()方法是延时加载,调用时只返回一个代理对象(只包含ID),并且如果没有该ID对应的数据会抛ObjectNotFoundException异常。
get()方法是实时加载,调用后就返回ID对应的记录,如果数据不存在则返回null对象。
为了测试一下效果,我们在hibernate的配置文件中加<propertyname="show_sql">true</property>和<property name="format_sql">true</property>。
注意看下面两段代码及结果的区别。
至于查不存在的数据,大伙就自己试试吧。今天的就打到这儿吧。下一篇我们来了解稍微高深那么一点点的知识吧。