听人说现在公司很少有人使用hibernate了,但笔者本科还是学了这个,把问题做一个概述,但不展开讲解,仅仅是帮助找到错误。
首先将要使用的jar包(hibernate核心类库以及相应的JDBC,笔者使用的是sql)导入项目,这个一般不存在问题。
重点在约束导入、核心配置文件(hibernate.cfg.xml)和映射文件(类名.hbm.xml也可使用Java注解)这三个点
- 约束导入
这个博主写的挺好的:https://blog.csdn.net/qq_40762011/article/details/81736037
- 映射文件
映射文件的作用是把类和数据库关联起来,下面是一个项目的范例,我会在最后附上我的目录结构
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.UserTable" table="usertable" dynamic-update="true">
<id name="userId" column="userId" >
<generator class="assigned"/>
</id>
<property name="userName" column="userName"/>
<property name="userTel" column ="userTel"/>
</class>
</hibernate-mapping>
- 核心配置文件
我使用的是xml进行配置,数据库用的是sql2008
<?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>
<!--数据库URL -->
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost:1433;databasename=Dept
</property>
<!--数据库用户 -->
<property name="hibernate.connection.username">sa</property>
<!--数据库用户密码 -->
<property name="hibernate.connection.password">123</property>
<!--数据库JDBC驱动 -->
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<!--每个数据库都有其对应的Dialect以匹配其平台特性 -->
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<!--指定当前session范围和上下文 -->
<property name="current_session_context_class">thread</property>
<!--是否将运行期生成的SQL输出到日志以供调试 -->
<property name="show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!--是否格式化SQL -->
<property name="format_sql">true</property>
<mapping resource="cn/UserTable.hbm.xml"/>
</session-factory>
</hibernate-configuration>
- 目录结构
resoure是创建的Source Folder,eclipse的特性会在Source Folder目录下查找配置文件